Decrypt JWT Token in C# - jwt

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

Related

How do I decrpyt a message with AES when I have only the encrypted message and a key in flutter?

How do I decrypt a message when I have only the message and the key?
I know the key (as a string), and the encrypted message is returned from my friend's API (as a string). My friend uses CryptoJS to encrypt with AES. How do I decrypt that message? I think my friend uses the default settings for everything (in CryptoJS).
I'm trying it with encrypt in flutter. The thing is encrypter.decrypt() accepts the type Encrypted and iv while I have the encrypted message as a String. How do I convert it to Encrypted? Also, how do I obtain the iv?
Here's an example of the known information (both are String)
Encrypted message: U2FsdGVkX1851cYw0S6LX/xhUwdy0R/1AlNun5L9Ykc=
Key Example: myKey111
I'm currently out of ideas.
Here's what I have currently
String key = 'myKey111';
String keyB64 = base64.encode(utf8.encode(key));
final keyKey = encrypt.Key.fromBase64(keyB64);
String code = "U2FsdGVkX1851cYw0S6LX/xhUwdy0R/1AlNun5L9Ykc=";
List<int> list = code.codeUnits;
Uint8List bytes = Uint8List.fromList(list);
final _encrypted = encrypt.Encrypted(bytes);
print('KEY TEST: ${keyKey.base64}');
final _encrypter = encrypt.Encrypter(encrypt.AES(
keyKey,
mode: encrypt.AESMode.cbc,
padding: 'PKCS7',
));
final iv = encrypt.IV.fromUtf8('myKey111');
final _decrypted = _encrypter.decrypt(_encrypted, iv: iv);

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`
}

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

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?