doulierong0334
2015-05-31 03:52
浏览 230
已采纳

RSA在Java和Go之间进行加密和解密

In java I encrypt a string by RSA : "Hello,I am plaintext string!@sina.com" then get:

kkkHf5QSXx8aDadk66AOysmV8LOi4vWUANal+7KV6va/5ZR7PSWGRS5bzbK4vMyK9FA5CLQolr2N B6ouPNWpgq3Af7Pn/f45+pDtKRsBLX8+q/Mw7TOYR525e7nVePDBLM2wLQZ4Gh5QMQzEI3Me3Zc3 030jRg0gEG13N/1EzMo=

But I tried many methods and couldn't decrypt it in go. What's the problem?

Any help will be appreciated, thanks.

Here is my code:

java:

public static void main(String[] args) throws Exception {  
String pubKey_from_go="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZsfv1qscqYdy4vY+P4e3cAtmv"+
            "ppXQcRvrF1cB4drkv0haU24Y7m5qYtT52Kr539RdbKKdLAM6s20lWy7+5C0Dgacd"+
            "wYWd/7PeCELyEipZJL07Vro7Ate8Bfjya+wltGK9+XNUIHiumUKULW4KDx21+1NL"+
            "AUeJ6PeW+DAkmJWF6QIDAQAB";

String plainText = "Hello,I am  plaintext string!@sina.com"; 
String encryptString=encByGoPubKey(pubKey_from_go,plainText);
}
public static String encByGoPubKey(String pubkey_from_go,String plainText) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");//Cipher.getInstance("RSA/ECB/PKCS1Padding");  
    byte[] plainTextBytes = plainText.getBytes();  

    PublicKey pubkey_go=getPublicKey(pubkey_from_go);
    cipher.init(Cipher.ENCRYPT_MODE, pubkey_go);  
    byte[] enBytes = cipher.doFinal(plainTextBytes);  
    String encryptString = (new BASE64Encoder()).encode(enBytes);  
    return encryptString;   
}
public static PublicKey getPublicKey(String key) throws Exception {  
  byte[] keyBytes;  
  keyBytes = (new BASE64Decoder()).decodeBuffer(key);  

  X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  
  KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
  PublicKey publicKey = keyFactory.generatePublic(keySpec);  
  return publicKey;  
}  

Go:

import (
        "crypto/rand"
        "crypto/rsa"
        // "crypto/sha1"
        "crypto/x509"
        "encoding/base64"
        "encoding/pem"
        "errors"
        // "flag"
        "fmt"
        "github.com/astaxie/beego"
    )
var publicKey = []byte(`
    -----BEGIN PUBLIC KEY-----
    MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZsfv1qscqYdy4vY+P4e3cAtmv
    ppXQcRvrF1cB4drkv0haU24Y7m5qYtT52Kr539RdbKKdLAM6s20lWy7+5C0Dgacd
    wYWd/7PeCELyEipZJL07Vro7Ate8Bfjya+wltGK9+XNUIHiumUKULW4KDx21+1NL
    AUeJ6PeW+DAkmJWF6QIDAQAB
    -----END PUBLIC KEY-----
    `)
    var privateKey = []byte(`
    -----BEGIN RSA PRIVATE KEY-----
    MIICXQIBAAKBgQDZsfv1qscqYdy4vY+P4e3cAtmvppXQcRvrF1cB4drkv0haU24Y
    7m5qYtT52Kr539RdbKKdLAM6s20lWy7+5C0DgacdwYWd/7PeCELyEipZJL07Vro7
    Ate8Bfjya+wltGK9+XNUIHiumUKULW4KDx21+1NLAUeJ6PeW+DAkmJWF6QIDAQAB
    AoGBAJlNxenTQj6OfCl9FMR2jlMJjtMrtQT9InQEE7m3m7bLHeC+MCJOhmNVBjaM
    ZpthDORdxIZ6oCuOf6Z2+Dl35lntGFh5J7S34UP2BWzF1IyyQfySCNexGNHKT1G1
    XKQtHmtc2gWWthEg+S6ciIyw2IGrrP2Rke81vYHExPrexf0hAkEA9Izb0MiYsMCB
    /jemLJB0Lb3Y/B8xjGjQFFBQT7bmwBVjvZWZVpnMnXi9sWGdgUpxsCuAIROXjZ40
    IRZ2C9EouwJBAOPjPvV8Sgw4vaseOqlJvSq/C/pIFx6RVznDGlc8bRg7SgTPpjHG
    4G+M3mVgpCX1a/EU1mB+fhiJ2LAZ/pTtY6sCQGaW9NwIWu3DRIVGCSMm0mYh/3X9
    DAcwLSJoctiODQ1Fq9rreDE5QfpJnaJdJfsIJNtX1F+L3YceeBXtW0Ynz2MCQBI8
    9KP274Is5FkWkUFNKnuKUK4WKOuEXEO+LpR+vIhs7k6WQ8nGDd4/mujoJBr5mkrw
    DPwqA3N5TMNDQVGv8gMCQQCaKGJgWYgvo3/milFfImbp+m7/Y3vCptarldXrYQWO
    AQjxwc71ZGBFDITYvdgJM1MTqc8xQek1FXn1vfpy2c6O
    -----END RSA PRIVATE KEY-----
    `
    func RsaEncrypt(origData []byte, pubKey []byte) ([]byte, error) {
        block, _ := pem.Decode(pubKey)
        if block == nil {
            return nil, errors.New("public key error")
        }
        pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
        if err != nil {
            return nil, err
        }
        pub := pubInterface.(*rsa.PublicKey)
        return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
    }

    func RsaDecrypt(ciphertext []byte, privKey []byte) ([]byte, error) {
        block, _ := pem.Decode(privKey)
        if block == nil {
            return nil, errors.New("private key error!")
        }
        priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
        if err != nil {
            return nil, err
        }
        return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
    }
var data64 string = `kkkHf5QSXx8aDadk66AOysmV8LOi4vWUANal+7KV6va/5ZR7PSWGRS5bzbK4vMyK9FA5CLQolr2NB6ouPNWpgq3Af7Pn/f45+pDtKRsBLX8+q/Mw7TOYR525e7nVePDBLM2wLQZ4Gh5QMQzEI3Me3Zc3030jRg0gEG13N/1EzMo=`
    func main() {
        data, _ := base64.StdEncoding.DecodeString(data64)
        origData, _ := RsaDecrypt(data, privateKey)
        fmt.Println("rsa-------" + string(origData))
    }
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doubingguan3425 2015-05-31 04:39
    已采纳

    Try to use padding in Java to encrypt. I know nothing about "go" but in Java you are encrypting message with no padding.

    Cipher cipher = Cipher.getInstance("RSA");
    

    in this code snippet change "RSA" to "RSA/ECB/PKCS1Padding" since in "go" as I see you are using some function called "DecryptPKCS1v15", PKCS1 v1.5 standard itself means the PKCS#1 padding to be used. Hope it helps you.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题