admin管理员组文章数量:1415684
I have a scenario where I need to use RSA public key encryption standard with JavaScript and Golang. I need to encrypt data in JavaScript using public key and decrypt the same in Golang using the private key. I tried using PKCS#1(travst library for JavaScript and crypto/rsa for Golang), but failed in decryption. Can anyone suggest solutions for this?
I tried all possible solutions and researched many documents, but still I couldn't find a proper method. If I do encrypt and decrypt within golang, its working fine. But there is some integration problem between javascript and golang. I am not sure about the padding methodology used in javasript.
This is my golang code to decrypt:
func Decrypt(encryptedData, label []byte) (decryptedData []byte) {
var err error
var block *pem.Block
var private_key *rsa.PrivateKey
if block, _ = pem.Decode([]byte(privatKeyData)); block == nil || block.Type != "RSA PRIVATE KEY" { //privatKeyData is in string format
log.Fatal("No valid PEM data found")
}
//Read Private Key
if private_key, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
log.Fatalf("Private key can't be decoded: %s", err)
}
//Decrypt
if decrypted, err = rsa.DecryptPKCS1v15(rand.Reader, private_key, encryptedData); err != nil {
log.Println(err)
}
return
}
I have a scenario where I need to use RSA public key encryption standard with JavaScript and Golang. I need to encrypt data in JavaScript using public key and decrypt the same in Golang using the private key. I tried using PKCS#1(travst library for JavaScript and crypto/rsa for Golang), but failed in decryption. Can anyone suggest solutions for this?
I tried all possible solutions and researched many documents, but still I couldn't find a proper method. If I do encrypt and decrypt within golang, its working fine. But there is some integration problem between javascript and golang. I am not sure about the padding methodology used in javasript.
This is my golang code to decrypt:
func Decrypt(encryptedData, label []byte) (decryptedData []byte) {
var err error
var block *pem.Block
var private_key *rsa.PrivateKey
if block, _ = pem.Decode([]byte(privatKeyData)); block == nil || block.Type != "RSA PRIVATE KEY" { //privatKeyData is in string format
log.Fatal("No valid PEM data found")
}
//Read Private Key
if private_key, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
log.Fatalf("Private key can't be decoded: %s", err)
}
//Decrypt
if decrypted, err = rsa.DecryptPKCS1v15(rand.Reader, private_key, encryptedData); err != nil {
log.Println(err)
}
return
}
Share
Improve this question
edited Mar 18, 2016 at 5:14
Sujai Sivasamy
asked Mar 17, 2016 at 8:03
Sujai SivasamySujai Sivasamy
1,2763 gold badges18 silver badges33 bronze badges
5
- 2 can you post the error received? or show us the decryption result. – Endre Simo Commented Mar 17, 2016 at 8:10
- 1 @SimoEndre Error: crypto/rsa: decryption error (i just received this error) – Sujai Sivasamy Commented Mar 17, 2016 at 9:34
- 1 I tried decoding the encrypted data from base64 format and decrypted it, but still received the same error – Sujai Sivasamy Commented Mar 17, 2016 at 9:37
- Share your code, to have an idea on the issue. – Endre Simo Commented Mar 17, 2016 at 9:51
- Assume you mean jsencrypt library? – Mark Commented Mar 19, 2016 at 9:45
2 Answers
Reset to default 3It's possible to encrypt in javascript and decrypt in Go. Using the library you refer to, jsencrypt:
Create public & private key pair:
openssl genrsa -out key.pem
openssl rsa -in key.pem -pubout > pub.pem
Encryption in javascript:
var encrypt = new JSEncrypt();
encrypt.setPublicKey($('#pubkey').val());
var encrypted = encrypt.encrypt($('#message').val());
$.post("/decrypt", encrypted, function(response) {
$("#decrypted").val(response);
});
Decryption in Go:
func handleDecrypt(w http.ResponseWriter, r *http.Request) {
decoder := base64.NewDecoder(base64.StdEncoding, r.Body)
defer r.Body.Close()
encrypted, err := ioutil.ReadAll(decoder)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
data, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, encrypted)
if err != nil {
http.Error(w, "decrypt error", http.StatusBadRequest)
log.Println(err)
return
}
fmt.Fprint(w, string(data))
}
Update: the privateKey variable is a *rsa.PrivateKey derived from the private key file created by openssl, in this case the "key.pem" file. A pem file is a Base64 encoded DER certificate, eg, -----BEGIN RSA PRIVATE KEY----- and -----END RSA PRIVATE KEY----- show a private key in PEM format. Go standard library provides the x509.ParsePKCS1PrivateKey() method to parse a pem encoded key from a byte slice.
So loading the key into Go might look something like this:
keyBytes, err := ioutil.ReadFile("path/to/key.pem")
if err != nil { ... }
privateKey, err := x509.ParsePKCS1PrivateKey(keyBytes)
if err != nil { ... }
1:You can encrypt cleartext in javascript reference from.
https://github./travist/jsencrypt
var encrypt = new JSEncrypt();
encrypt.setPublicKey($('#pubkey').val());
var encrypted = encrypt.encrypt($('#input').val());
2:Be aware of that the jsencrypt has already done encrypt and base64encode.
Be aware of that jsencrypt use PKCS1 not OAEP
3: Base64decode in golang and decrypt message from step 1.
var encrypted := 'change this to the encrypted text your js sent'
privateKey,_ = ioutil.ReadFile("private.pem")
cipherText,_ := base64.StdEncoding.DecodeString(encrypted)
originText,_ :=RsaDecrypt([]byte(cipherText))
decrypt function
func RsaDecrypt(cipherText []byte) ([]byte, error) {
block, _ := pem.Decode(privateKey)
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)
}
now you get the encrypted text originText
reference from
https://segmentfault./q/1010000002505932
4: Further more, you can generate key pair in go
func GenRsaKey(bits int) error {
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return err
}
derStream := x509.MarshalPKCS1PrivateKey(privateKey)
block := &pem.Block{
Type: "privete key",
Bytes: derStream,
}
file, err := os.Create("private.pem")
if err != nil {
return err
}
err = pem.Encode(file, block)
if err != nil {
return err
}
publicKey := &privateKey.PublicKey
derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return err
}
block = &pem.Block{
Type: "public key",
Bytes: derPkix,
}
file, err = os.Create("public.pem")
if err != nil {
return err
}
err = pem.Encode(file, block)
if err != nil {
return err
}
return nil
}
本文标签: goRSA Javascript encryption and Golang decryptionStack Overflow
版权声明:本文标题:go - RSA Javascript encryption and Golang decryption - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745217708a2648248.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论