Skip to content

Instantly share code, notes, and snippets.

@jastisriradheshyam
Created August 17, 2019 19:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jastisriradheshyam/95b32393cb04f3dbb3ba2ba9d75f72ec to your computer and use it in GitHub Desktop.
Save jastisriradheshyam/95b32393cb04f3dbb3ba2ba9d75f72ec to your computer and use it in GitHub Desktop.
RSA OAEP, encryption with Golang and decryption with NodeJS (node-rsa)
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;
};
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