Postman RSA Encryption - rsa

I would like to utilize postman to test a REST API that requires one of the input fields to be encrypted with RSA encryption.
I see that postman provides the functionality through require('crypto-js') to encrypt using AES encryption, but I that library does not provide RSA encryption. How can I use post man to automate RSA encryption?
The flow would work like this:
Call a REST API that returns an RSA public key
Store the RSA public key in a variable
Utilize that public key to encrypt an value in the following request
before sending

I have created a little ¨library¨ to use cryptographic methods in Postman Pre-request and Tests script, RSA is totally supported, have a look to the tutorial here, is very easy to use.
https://joolfe.github.io/postman-util-lib/
Best Regards.
Here is an example of how to RSA encrypt using the 'RSAOAEP' alg:
// RSAOAEP signature example
const pubkey = '-----BEGIN PUBLIC KEY-----\n' +
'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAstXEkU/agbNkQgh6a9DV\n' +
'C/WXGmNy8g+hdTOBhYUk5PfZCwTNt5SCYBLjIPhs2ZRrNuCN3PhwHRQPQOTsS6Nl\n' +
'Bzw+SjPVFBhPcbMHbJWnC87Q5ID/uAuwJjcUQXUTVspwIgfRmHvuuT7w7AYnCNvz\n' +
'B5TuPj2vVH8rij9BXkAHambaeGG7L10MPeUiVU6M0F/QKCJhEWAYGEt4NffSXETx\n' +
'zHSl8nyXxVJfnjxVhnZyZVXTIpLwvRy04hnkAoFexh7npRtnQdsLuIHtaJsm7gFY\n' +
'mxhr3Nxbh9p1pC7fHpJ+jMcxAAhA07WqYf6lOsxXHfPav1FEMX214YTsKTw68xqo\n' +
'DwIDAQAB\n' +
'-----END PUBLIC KEY-----\n'
const fileContent = 'My file content comes here...'
const keyObj = pmlib.rs.KEYUTIL.getKey(pubkey)
const encHex = pmlib.rs.KJUR.crypto.Cipher.encrypt(fileContent, keyObj, 'RSAOAEP')
console.log(encHex)
// will return the hexadecimal encoded, can be converted to many format ussing the library too

I dit it.
you need https://github.com/digitalbazaar/forge
and compile it, not from cdn, can not work
load from your script
1.load script
var server = postman.getEnvironmentVariable("server");
if (!postman.getEnvironmentVariable("forgeJS")) {
pm.sendRequest("http://" + server + "/res/forge.js", function(err, res) {
if (err) {
console.log(err);
} else {
postman.setEnvironmentVariable("forgeJS", res.text());
}
})
}
2.eval script and encrypt
var password = '123456';
var public_key = '-----BEGIN PUBLIC KEY-----\n' +
pm.environment.get("rsaKey") + '\n' +
'-----END PUBLIC KEY-----';
var jsscript = pm.environment.get("forgeJS");
eval(jsscript);
console.info(public_key)
var publicKey = forge.pki.publicKeyFromPem(public_key);
var encryptedText = forge.util.encode64(publicKey.encrypt("123456", 'RSA-OAEP', { // server Java private decrypt
md: forge.md.sha256.create(),
mgf1: {
md: forge.md.sha1.create()
}
}));
postman.setEnvironmentVariable("password", encryptedText);

Related

Decrypt JWT Token in C#

Hello I'm trying to see if they're any JWT token library similar to JOSE-JWT that also works on a Linux machine during runtime.
This is what I currently have in code that decrypts a token and grabs what I need.
private IamTokenDecrypted DecryptToken(string idToken)
{
byte[] key = WebEncoders.Base64UrlDecode(_ssoEncryptionKeyInfo.JsonWebKey.K);
string json = Jose.JWT.Decode(idToken, key, JweAlgorithm.DIR, JweEncryption.A256GCM);
var result = Jose.JWT.Payload(json);
var iamTokenDecrypted = JsonConvert.DeserializeObject<IamTokenDecrypted>(result);
return iamTokenDecrypted;
}
I have a security key and and as you see it has some encryption in it

How to store long public key string in Dart/Flutter?

I am testing out some PGP encryption in Flutter using the openpgp package. I'm trying to encrypt using a public key, but I'm not sure how to store such a long string.
Here is their example:
var result = await OpenPGP.encrypt("text","[publicKey here]");
Here is a example public key, but I can't store it properly. Even using r"key" I get many errors.
I found in a example document for simple_rsa this is how they store the key:
final PUBLIC_KEY =
"MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBuAGGBgg9nuf6D2c5AIHc8" +
"vZ6KoVwd0imeFVYbpMdgv4yYi5obtB/VYqLryLsucZLFeko+q1fi871ZzGjFtYXY" +
"9Hh1Q5e10E5hwN1Tx6nIlIztrh5S9uV4uzAR47k2nng7hh6vuZ33kak2hY940RSL" +
"H5l9E5cKoUXuQNtrIKTS4kPZ5IOUSxZ5xfWBXWoldhe+Nk7VIxxL97Tk0BjM0fJ3" +
"8rBwv3++eAZxwZoLNmHx9wF92XKG+26I+gVGKKagyToU/xEjIqlpuZ90zesYdjV+" +
"u0iQjowgbzt3ASOnvJSpJu/oJ6XrWR3egPoTSx+HyX1dKv9+q7uLl6pXqGVVNs+/" +
"AgMBAAE=";

Using HyperLedger Fabric certificates for signing a message

We have generated public and private keys in Hyperledger Fabric using its API which are getting stored in crypto_material folder.
Now, on one machine we want to sign a message using private key and verify its validity on second machine using corresponding public key. To achieve this task we have written code as follows.
var crypto = require("crypto");
var secp256k1 = require("secp256k1");
var fs = require("fs");
var sha256 = require('sha256')
let pub_key_file = "./keyfiles/4d4a0d669d507ff05c73c9e1ca40fb5f909f9806df138a82767a739e9de31240-pub"
fs.access(pub_key_file, fs.F_OK, (err) => {
if (err) {
console.log("readfile error : ", err);
return;
}
})
var public_key = fs.readFileSync(pub_key_file);
// Reading private key from file system.
let priv_key_file = "./keyfiles/4d4a0d669d507ff05c73c9e1ca40fb5f909f9806df138a82767a739e9de31240-priv"
fs.access(priv_key_file, fs.F_OK, (err) => {
if (err) {
console.log("readfile error : ", err);
return;
}
})
var private_key = fs.readFileSync(priv_key_file);
var privKey = new Uint8Array(sha256(private_Key).match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
var pubKey = new Uint8Array(sha256(public_Key).match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
console.log(pubKey instanceof Uint8Array) //returning true here
console.log("value : ", secp256k1.privateKeyVerify(privKey)); //returning true here
console.log("value : ", secp256k1.publicKeyVerify(pubKey)); // Getting error like expected public key to be an Uint8Array with length [33, 65] hyperledger fabric
Why the secp256k1 module is successfully verifying privateKey but failing with publicKey.
I assume that you performed an enroll after you registered the identity using register.
You will actually have multiple issues with what you are attempting to do.
Fabric CA generates EC keys using NIST-approved curves (e.g. secp256r1,secp384r1) and not secp256k1 used by Bitcoin
Fabric CA produces a private key and an X509 certificate from the corresponding public key
The private key and X509 certificate are returned as PEM-encoded blobs as well.
There are many libraries out there which you can use to sign/verify using PEM encoded private keys and X509 certificates. jsrsasign is fairly straightforward.
You can also use some of the modules provided by the Fabric Node SDK as well depending on what you are doing.

jsonwebtoken package fails to verify user Office.context.mailbox.getUserIdentityToken result

I'm developing an Outlook web add-in.
I'm trying to verify a token that I'm passing to server side, through a node.js library, but it's failing and I can't understand why.
This is what I'm doing to retrieve the user identity token.
Office.context.mailbox.getUserIdentityTokenAsync(function(result) {
result.value // contains the token.
// send this value to server side, which I can see that it's working.
})
On the server side, I retrieve the token and do below:
token; // contains the token passed from the web-app.
const jwt = require('jsonwebtoken');
const request = require('request');
let decoded = jwt.decode(token, {complete: true});
// Get the key, we'll need this later since we'll have to
// find the matching key from the config file.
let key = decoded.header.x5t;
let amurl = JSON.parse(decoded.payload.appctx).amurl;
// Make a request to the url to get the configuration json file.
request(amurl, {}, (err, response, body) => {
let keys = JSON.parse(body).keys;
// Filter the keys so we get the one which we can verify.
let s = keys.filter(t => t.keyinfo.x5t === key);
let cert = s[0].keyvalue.value;
// Fails the verification.
console.log(jwt.verify(token, cert));
});
Just to clarify, I'm retrieving the token correctly and this npm package seems to be functioning fine for other jwt tokens. (So it's not really a configuration issue)
I have now found the answer to this question.
Just to re-iterate the problem was:
Office.context.mailbox.getUserIdentityToken method returns a jwt token.
When decoded this token contains an amurl field which points to the public certificate as a text.
When jsonwebtoken.verify(token, certText) is called, it's failing with the message invalid algorithm (even if you specify the algorithm from the token's header)
The problem was the formatting of the certificate text. jsonwebtoken package was looking for a particular formatting (splitted with 64 characters across each line along with the certificate begin and certificate end lines, so when formatted with method below - it started working properly.
The original code is taken from here: https://github.com/auth0/node-jsonwebtoken/issues/68 and formatted slightly to fit the needs.
/**
* #param {string} key - The certificate value retrieved from amurl property.
*/
formatKey: function(key) {
const beginKey = "-----BEGIN CERTIFICATE-----";
const endKey = "-----END CERTIFICATE-----";
const sanitizedKey = key.replace(beginKey, '').replace(endKey, '').replace('\n', '')
const keyArray = sanitizedKey.split('').map((l, i) => {
const position = i + 1
const isLastCharacter = sanitizedKey.length === position
if(position % 64 === 0 || isLastCharacter) {
return l + '\n'
}
return l
})
return `${beginKey}\n${keyArray.join('')}${endKey}\n`
}

RSA encryption issue in C#

I have an api that returns me public key. Here is a public key sample,
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ9AMIIBCgKCAQEAoqB1N9kugk4UKYnbh0fcg3qYyYKP0m4B
MjWd05ReeAdj+7JRYDEKO6xthDdVSdRO1/2V+YtY8DnXWnxRaICwu8235s3imZCyqgYnomPWdY+F
K540oTz/zug+9wbrlzt/WQFUU4lPlQbzm/Gjw8XfaCozT0e3bnWQcD7rORCOyuJgwSGgREjTv1ss
pgEaKTMknii9vpGZLeAXwoeIYROhuT4IoIkPDhtY0/UZiCi6v7Ja2dmy53VlWIkcm3rcnSJdvpXr
OgiHvaNABHmeymNycNqd6WUaysBRheluQ86nq/2nZPW0gcvmYt5zbMMYX3yY/n2WtAKeNQBAEW1q
b0s6MwIDAQAB
Now I need to encode string a=1&b=2 using RSA algorithm,
var key = await GetPublicKey();
var keyXml = "<RSAKeyValue><Modulus>" + key + "</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
EncrptedValue = CryptUtils.Encrypt(keyXml, "amount=1&currency=aed", RsaKeyLengths.Bit1024);
I am using CryptUtils class at https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack.Common/CryptUtils.cs.
Now I am sending the encrypted value to another server but another server guy telling me that the encrypted value is not corect. What I am doing wrong?