cong chen cong chen - 4 months ago 63x
Java Question

RSA OAEP , Golang Decrypt , Java Encrypt

The Android client encrypt message, the java code

Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");

byte[] publicBytes = Base64.decode(Configs.PUBLIC_KEY.getBytes("UTF-8"),Base64.DEFAULT);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);

cipher.init(Cipher.ENCRYPT_MODE, pubKey);

String plaintext = "test";

byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes("UTF-8"));
String chipertext = Base64.encodeToString(encryptedBytes,Base64.DEFAULT);
Log.d(TAG,"encrypted (chipertext) = " + chipertext);

The Golang server decrypt message, the golang code

func RsaDecrypt(encryptedString string) (string, error) {
base64DecodeBytes, err := base64.StdEncoding.DecodeString(encryptedString)
if err != nil {
return "", err
privateKeyBlock, _ := pem.Decode([]byte(privateKey))
var pri *rsa.PrivateKey
pri, parseErr := x509.ParsePKCS1PrivateKey(privateKeyBlock.Bytes)
if parseErr != nil {
return "", parseErr
decryptedData, decryptErr := rsa.DecryptOAEP(sha1.New(), rand.Reader, pri, base64DecodeBytes, nil)
if decryptErr != nil {
return "", decryptErr

return string(decryptedData), nil

and the error in golang :
crypto/rsa: decryption error

I can't change the code on the server, so how to change the code in Java?

Need your help



The hash functions in the two programs are not the same. In Java version, SHA-256 is used, but in Go version, SHA-1 is used.

You can try to use RSA/ECB/OAEPWithSHA-1AndMGF1Padding in the Java side.