I (1) create Public key in Go and send it for Android (2) android use below code to Encrypt it's data to send to Go with string type (3) Go get string data and try to Decrypt it, but it can't.
My Go code:
// DecryptWithPrivateKey decrypts data with private key
func DecryptWithPrivateKey(ciphertext []byte, priv *rsa.PrivateKey) []byte {
plaintext, err := rsa.DecryptPKCS1v15(rand.Reader, priv , ciphertext)
if err != nil {
log.Println(err)
}
return plaintext
}
.
.
.
so.On("serverpublic", func(msg string) {
mes := []byte(msg)
decbyte :=DecryptWithPrivateKey(data,pr)
str := fmt.Sprintf("%s", decbyte)
log.Println("encript data from Android ---->" , str)
})
Android studio code:
public final static String chi="RSA/NONE/PKCS1Padding"; //RSA/ECB/PKCS1Padding
private static byte[] dec4golang(byte[] src) throws Exception {
Cipher cipher = Cipher.getInstance(chi);
cipher.init(Cipher.DECRYPT_MODE, serverrk);
return cipher.doFinal(src);
}
private static byte[] enc4golang(String text, PublicKey pubRSA) throws Exception{
Cipher cipher = Cipher.getInstance(chi);
cipher.init(Cipher.ENCRYPT_MODE, pubRSA);
return cipher.doFinal(text.getBytes("UTF-8")); //i also advice you to use: .getBytes("UTF-8"); instead of data.getBytes();
}
public final static String enc4golang(String text){
try {
return byte2hex(enc4golang(text, serveruk));
// return enc4golang(text, serveruk).toString();
// return new String(enc4golang(text, serveruk), "UTF-8");
// return new String(enc4golang(text, serveruk), Charset.forName("utf-8"));
// return Base64.encodeToString(enc4golang(text, serveruk), Base64.DEFAULT);///nodejs
// return Base64Utils.encodeToString(enc4golang(text, serveruk));
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
public static String byte2hex(byte[] b)
{
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n ++)
{
stmp = Integer.toHexString(b[n] & 0xFF);
if (stmp.length() == 1)
hs += ("0" + stmp);
else
hs += stmp;
}
return hs.toUpperCase();
}
I think my problem is in these lines:
chi="RSA/NONE/PKCS1Padding"; //RSA/ECB/PKCS1Padding
OR
return byte2hex(enc4golang(text, serveruk));