How to create PEM formatted key from email and password? - rsa

I am using Hybrid-Crypto.js for playing around with public/private key encryption.
This function creates a random PEM-formatted RSA keypair
// Generate 2048 bit RSA key pair
rsa.generateKeypair(function(keypair) {
// Callback function receives new 2048 bit keypair as an argument
var publicKey = keypair.publicKey;
var privateKey = keypair.privateKey;
}, 2048); // Key size
However, I would like to create a keypair derived from email and password like being known from openpgp.js
var options = {
userIds: [{ name: 'Alicee', email: 'alice#example.com' }],
numBits: 2048,
passphrase: 'secretttoo'
};
var publicKeyAlice;
var privateKeyAlice;
openpgp.generateKey(options).then(key => {
privateKeyAlice = key.privateKeyArmored;
publicKeyAlice = key.publicKeyArmored;
console.log('Key generated');
});
Is there a way to create PEM/RSA keypairs like PGP-keys from fixed sources such that every time the same keypair gets created when the same inputs (email/password) is entered?

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

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.

Postman RSA Encryption

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

Encrypt string using PCLCrypto

I have a RSA key which I got from a service provider. I just want to encrypt the string data with that RSA key by using the PCLCrypto library. I don't want to create the RSA key by using PCLCrypto. I only wanted to encrypt the data. (I am developing a PCL component in xamarin.)
Follow the documentation for AES encryption and modify it for RSA. Use AsymmetricAlgorithm.RsaPkcs1 as algorithm provider.
Below example is for AES.
byte[] keyMaterial;
byte[] data;
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
// The IV may be null, but supplying a random IV increases security.
// The IV is not a secret like the key is.
// You can transmit the IV (w/o encryption) alongside the ciphertext.
var iv = WinRTCrypto.CryptographicBuffer.GenerateRandom(provider.BlockLength);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data, iv);
// When decrypting, use the same IV that was passed to encrypt.
byte[] plainText = WinRTCrypto.CryptographicEngine.Decrypt(key, cipherText, iv);

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?