2016-06-14 04:16

RSA OAEP,Golang解密,Java加密


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


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • doufutao4428 doufutao4428 5年前

    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.

    点赞 评论 复制链接分享