Created
August 17, 2019 19:06
-
-
Save jastisriradheshyam/95b32393cb04f3dbb3ba2ba9d75f72ec to your computer and use it in GitHub Desktop.
RSA OAEP, encryption with Golang and decryption with NodeJS (node-rsa)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const nodeRSA = require('node-rsa'); | |
/** | |
* return the decrypted Data (RSA OAEP Encryption) | |
* @param {string} RSAPrivateKey | |
* @param {string} EncrypteDataBuffer | |
* @returns {string} Data decrypted data | |
*/ | |
var RSA_OAEP_Decrypt = function(RSAPrivateKey, EncrypteDataBuffer){ | |
// ----- Setting RSA OAEP Configuration [ start ] ----- | |
let RSAPrivate = new nodeRSA(RSAPrivateKey); | |
RSAPrivate.setOptions({ | |
environment: 'browser', | |
encryptionScheme: { | |
scheme: 'pkcs1_oaep', | |
hash: 'sha256', | |
label: 'RSA_LABEL' | |
} | |
}); | |
// ----- Setting RSA OAEP Configuration [ end ] ----- | |
let encryptedData = Buffer.from(EncrypteDataBuffer, "hex"); | |
let data = RSAPrivate.decrypt(encryptedData); | |
return data; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"crypto/rand" | |
"crypto/rsa" | |
"crypto/x509" | |
"encoding/hex" | |
"encoding/pem" | |
"errors" | |
) | |
const ( | |
RSA_LABEL = "RSA_LABEL" | |
) | |
// EncryptWithRSAPublicKey encrypts the data with RSA public key | |
func EncryptWithRSAPublicKey(plainData []byte, RSAPublicKeyString string) (string, error) { | |
// ----- Converting RSA Public key string to Public key object [ start ] ----- | |
block, _ := pem.Decode([]byte(RSAPublicKeyString)) | |
if block == nil { | |
return "", errors.New("failed to parse PEM block containing the public key") | |
} | |
RSAPublicKey, err := x509.ParsePKIXPublicKey(block.Bytes) | |
if err != nil { | |
return "", errors.New("failed to parse DER encoded public key: "+err.Error()) | |
} | |
// ----- Converting RSA Public key string to Public key object [ end ] ----- | |
// encrypting Data | |
randomSource := rand.Reader | |
encryptedDataBytes, err := rsa.EncryptOAEP(sha256.New(), randomSource, RSAPublicKey.(*rsa.PublicKey), plainData, []byte(RSA_LABEL)) | |
if err != nil { | |
return "", err | |
} | |
// hex encoding | |
encryptedData := hex.EncodeToString(encryptedDataBytes) | |
return encryptedData, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference: golang cross platform decrypt nodeJS encrypt · Issue #105 · rzcoder/node-rsa