RSA encrypt and decrypt between java and go

huangapple go评论93阅读模式
英文:

RSA encrypt and decrypt between java and go

问题

在Java中,我使用RSA加密了一个字符串:"Hello,I am plaintext string!@sina.com",然后得到了加密后的结果。但是我尝试了很多方法,无法在Go中解密它。有什么问题吗?感谢任何帮助。

以下是你的代码:

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 PUBL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ZGBFDITYvdgJM1MTqc8xQek1FXn1vfpy2c6O
-----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))
}

希望对你有所帮助!

英文:

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

得分: 1

尝试在Java中使用填充(padding)进行加密。我对"go"一无所知,但在Java中,你正在进行没有填充的消息加密。

在这段代码中,将"RSA"更改为"RSA/ECB/PKCS1Padding",因为根据我所看到的"go"代码,你正在使用名为"DecryptPKCS1v15"的某个函数,而PKCS1 v1.5标准本身就意味着要使用PKCS#1填充。希望对你有所帮助。

英文:

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.

huangapple
  • 本文由 发表于 2015年5月31日 11:52:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/30553653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定