Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create RSA Token in nodejs

I'm trying to authenticate to a REST API using encryption.

First I need to call the API to get an encryptionKey and a timestamp. The encryptionKey is in Base 64 format.

Then I need to create a RSAToken using the key and finaly encrypt the password using password + "|" + timestamp.

This is some sample code using python to authenticate to the API

key, timestamp = get_encryption_key()
decoded_key = key.decode('base64')
rsa_key = RSA.importKey(decoded_key)
encrypted = rsa_key.encrypt(password + '|' + str(timestamp), 'x')
encrypted_password = encrypted[0]

and

import base64
from Crypto.PublicKey import RSA
r = requests.get(my_url, headers=headers)

myData = r.json()
decoded = base64.b64decode(myData['encryptionKey'])
key = RSA.importKey(decoded)
enc = key.encrypt(password + '|' + str(myData['timeStamp']), 'x')
encryptedPassword = enc[0]

session = "/session"
my_url = url + session

payload = {"identifier": identifier,
"password": encryptedPassword,
"encryptedPassword": "True"
}

Any hints to achieve this under Node?

like image 264
yves Avatar asked Nov 09 '22 18:11

yves


1 Answers

You can use crypto.publicEncrypt to encrypt your password. Notice the padding, you might want to use the right padding that is being used in your Python script.

const crypto = require('crypto');
const constants = require('constants');
const decodedKey = Buffer(encriptionKey, 'base64').toString();

const encryptedPassword = crypto.publicEncrypt({
    key: decodedKey,
    padding : constants.RSA_PKCS1_OAEP_PADDING
} , Buffer(`${password}|${timestamp}`));

Check out this node.js test to find out more examples for different padding.

like image 173
hassansin Avatar answered Nov 15 '22 06:11

hassansin