RSA Javascript encryption and Golang decryption

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

RSA Javascript encryption and Golang decryption

问题

我有一个场景,需要在JavaScriptGolang中使用RSA公钥加密标准。我需要在JavaScript中使用公钥加密数据,并在Golang中使用私钥解密相同的数据。
我尝试使用PKCS#1(JavaScript中的travst库和Golang中的crypto/rsa库),但解密失败。有人可以提供解决方案吗?

我尝试了所有可能的解决方案,并研究了许多文档,但仍然找不到合适的方法。如果我在Golang内部进行加密和解密,一切正常。但是JavaScript和Golang之间存在一些集成问题。我不确定JavaScript中使用的填充方法。

这是我的Golang解密代码:

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
}

答案1

得分: 3

可以使用你提到的库jsencrypt在JavaScript中进行加密,然后在Go中进行解密。

首先,你需要创建公钥和私钥对。你可以使用以下命令:

openssl genrsa -out key.pem
openssl rsa -in key.pem -pubout > pub.pem

在JavaScript中进行加密:

var encrypt = new JSEncrypt();
encrypt.setPublicKey($('#pubkey').val());

var encrypted = encrypt.encrypt($('#message').val());

$.post("/decrypt", encrypted, function(response) {
    $("#decrypted").val(response);
});

在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))
}

更新:privateKey变量是从由openssl创建的私钥文件(在这个例子中是"key.pem"文件)派生的*rsa.PrivateKey。pem文件是一个Base64编码的DER证书,例如,"-----BEGIN RSA PRIVATE KEY-----"和"-----END RSA PRIVATE KEY-----"表示PEM格式的私钥。Go标准库提供了x509.ParsePKCS1PrivateKey()方法,用于从字节切片中解析pem编码的密钥。

因此,将密钥加载到Go中可能如下所示:

keyBytes, err := ioutil.ReadFile("path/to/key.pem")
if err != nil { ... }

privateKey, err := x509.ParsePKCS1PrivateKey(keyBytes)
if err != nil { ... }

希望对你有所帮助!

英文:

It'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 { ... }

答案2

得分: 3

1:你可以使用JavaScript中的JSEncrypt库对明文进行加密。

var encrypt = new JSEncrypt();
encrypt.setPublicKey($('#pubkey').val());
var encrypted = encrypt.encrypt($('#input').val());

2:请注意,jsencrypt已经完成了加密和Base64编码。

请注意,jsencrypt使用的是PKCS1而不是OAEP。

3:在Go语言中进行Base64解码并解密第1步中的消息。

var encrypted := '将此更改为js发送的加密文本';
privateKey,_ = ioutil.ReadFile("private.pem")
cipherText,_ := base64.StdEncoding.DecodeString(encrypted)
originText,_ :=RsaDecrypt([]byte(cipherText))

解密函数:

func RsaDecrypt(cipherText []byte) ([]byte, error) {
    block, _ := pem.Decode(privateKey)
    if block == nil {
        return nil, errors.New("私钥错误!")
    }
    priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    if err != nil {
        return nil, err
    }

    return rsa.DecryptPKCS1v15(rand.Reader, priv, cipherText)
}

现在你得到了加密文本originText

4:此外,你可以在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:  "私钥",
        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:  "公钥",
        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
}
英文:

1:You can encrypt cleartext in javascript reference from.

> https://github.com/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.com/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
}

huangapple
  • 本文由 发表于 2016年3月17日 16:03:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/36054681.html
匿名

发表评论

匿名网友

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

确定