I sign the text message on the private RSA key, then I translate this signature in Base64, then back and check it in the public key. Why that verification shows that the signature is not valid. Does Base64 really break the signature text? What am I doing wrong?

Code example:

try { Signature ecp2 = Signature.getInstance("SHA256withRSA"); ecp2.initSign((PrivateKey) readKey(login+"private")); ecp2.update("123".getBytes()); byte[] tmps = ecp2.sign(); Log.d("TAG123", new String(tmps)); String s_b = Base64.encodeToString(tmps, Base64.DEFAULT); //signature_open_key = ecp.sign().toString(); //String str = new String(tmps); Signature ecp3 = Signature.getInstance("SHA256withRSA"); ecp3.initVerify((PublicKey ) readKey(login+"public" )); String gg = new String(Base64.decode(s_b.getBytes(), Base64.DEFAULT)); Log.d("TAG123", "clear base64"+gg); ecp3.update("123".getBytes()); byte[] tt = gg.getBytes(); Log.d("TAG123", "clear base64"+tt); if(ecp3.verify(tt)) { Log.d("TAG123", "signature test TRUE"); } else { Log.d("TAG123", "signature test FALSE"); } } catch (Exception e) { e.printStackTrace(); } 

Translation in Base64 in order to get rid of the characters ' otherwise in MySQL you can not write as this is a special character.

  • Look here at this question . I think a similar problem. - Mikhail Vaysman
  • one
    somehow strangely combines bytes and strings. Then comes the string encoding, then the byte. There may be a catch ... - DNS

1 answer 1

Dear DNS was right. As a result, the correct option for posterity

 try { Signature ecp2 = Signature.getInstance("SHA256withRSA"); ecp2.initSign((PrivateKey) readKey(login+"private")); ecp2.update("123".getBytes()); byte[] tmps = ecp2.sign(); Log.d("TAG123", new String(tmps)); byte[] s_b = Base64.encode(tmps, Base64.DEFAULT); String buff = new String(s_b,"UTF-8"); Signature ecp3 = Signature.getInstance("SHA256withRSA"); ecp3.initVerify((PublicKey ) readKey(login+"public")); byte[] gg = Base64.decode(buff.getBytes("UTF-8"), Base64.DEFAULT); ecp3.update("123".getBytes()); if(ecp3.verify(gg)) { Log.d("TAG123", "signature test TRUE"); } else { Log.d("TAG123", "signature test FALSE"); } } catch (Exception e) { e.printStackTrace(); }