Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encrypt through node.js of encrypted string using algorithm RSA/ECB/PKCS1Padding

I have encrypted string using algorithm RSA/ECB/PKCS1Padding through Java code now the same need to be encrypted using node.js. I don't know how to encrypt through node.js using algorithm RSA/ECB/PKCS1Padding . Any suggestions? the Java code is:

public static String encrypt(String source, String publicKey)
            throws Exception {
    Key key = getPublicKey(publicKey);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] b = source.getBytes();
    byte[] b1 = cipher.doFinal(b);
    return new String(Base64.encodeBase64(b1), "UTF-8");
}
like image 885
user3189069 Avatar asked Nov 24 '22 06:11

user3189069


1 Answers

node js code using the cryto library:

const crypto = require('crypto')

const encryptWithPublicKey = function(toEncrypt) {
  
  var publicKey = '-----BEGIN PUBLIC KEY-----****' //your public key
  
  var buffer = Buffer.from(toEncrypt, 'utf8');
  var encrypted = crypto.publicEncrypt({key:publicKey, padding : crypto.constants.RSA_PKCS1_PADDING}, buffer)
  return  encrypted.toString("base64");
  
}
like image 142
infinity Avatar answered Dec 23 '22 13:12

infinity