user3189069
user3189069

Reputation: 61

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");
}

Upvotes: 6

Views: 5266

Answers (1)

infinity
infinity

Reputation: 51

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");
  
}

Upvotes: 2

Related Questions