how to generate encrypted JWE with node-jose - node.js

I'm using node-jose v0.11.0 (https://www.npmjs.com/package/node-jose) for JWK and JWE operations. I have an RSA key in JWK format that I can load into a JWK key store and also extract again. However, when I try to encrypt anything, I get into the "error2", "unsupported algorithm". How is it possible that RSA is an unsupported algorithm?
import * as jose from "node-jose";
const webkey = {
"keys": [
{
"kty": "RSA",
"e": "AQAB",
"kid": "a024254d-0321-459f-9530-93020ce9d54a",
"key_ops": [
"encrypt"
],
"n": "jkHgYN98dlR2w7NX-gekCWaCdbxs7X4XXh52DVQrK--krwUYqRbBIUEw1bV8KX0ox6TLt-e6wpYsYYFUItSd5ySqohHRMq1IhyE2zpEC95BA9V7VrFUYnczf1bd5c-aR079aoz5JPXfqx01TzNfxWBb04SlRjsmJeY1v6JrDUI5U0FSOmnJTb3tSS6Szrvi_qOyViYp4v9V2_OVYy45kF_LQQy-pr-kP4gapXL235cieeTW6UvkhzaPT2D-JKyzVjjjgnfRXr8Ox9I9c4wpef2-5nPPeafB5EnOMpJE11KzO_8xxiTGUywPPLQagBvY35gkhQbYS2dv3NGIVSLZHFw"
}
]
};
console.log("webkey", webkey);
//generate key store from public JWK
jose.JWK.asKeyStore(webkey)
.then((result) => {
console.log("Key Store", JSON.stringify(result.toJSON()));
let keyStore = result;
//get the key to encrypt
const encryptionKey: jose.JWK.Key = keyStore.get(webkey.keys[0].kid);
const output = jose.util.base64url.encode("Hello World");
const output2 = jose.util.asBuffer(output);
//encrypting content
jose.JWE.createEncrypt(encryptionKey)
.update(output2)
.final()
.then((jweInGeneralSerialization) => {
console.log("Encryption result", JSON.stringify(jweInGeneralSerialization));
}, (error) => {
console.log("error2", error.message);
});
}, (error) => {
console.log("error1", error.message);
})
The output is as follows:
'webkey', Object{keys: [Object{kty: ..., e: ..., kid: ..., key_ops: ..., n: ...}]}
'Key Store', '{"keys":[{"kty":"RSA","kid":"a024254d-0321-459f-9530-93020ce9d54a","key_ops":["encrypt"],"e":"AQAB","n":"jkHgYN98dlR2w7NX-gekCWaCdbxs7X4XXh52DVQrK--krwUYqRbBIUEw1bV8KX0ox6TLt-e6wpYsYYFUItSd5ySqohHRMq1IhyE2zpEC95BA9V7VrFUYnczf1bd5c-aR079aoz5JPXfqx01TzNfxWBb04SlRjsmJeY1v6JrDUI5U0FSOmnJTb3tSS6Szrvi_qOyViYp4v9V2_OVYy45kF_LQQy-pr-kP4gapXL235cieeTW6UvkhzaPT2D-JKyzVjjjgnfRXr8Ox9I9c4wpef2-5nPPeafB5EnOMpJE11KzO_8xxiTGUywPPLQagBvY35gkhQbYS2dv3NGIVSLZHFw"}]}'
'error2', 'unsupported algorithm'
Update
I digged around a bit in the actual code and found in "basekey.js" that the error is thrown because the algorithms of the library are empty.
Object.defineProperty(this, "encrypt", {
value: function(alg, data, props) {
// validate appropriateness
if (this.algorithms("encrypt").indexOf(alg) === -1) {
console.log("Algorithm USED", alg
);
console.log("All algorithms", this.algorithms("encrypt"))
return Promise.reject(new Error("unsupported algorithm"));
}
The output here is:
'Algorithm USED', 'A128CBC-HS256'
'All algorithms', []

I have an example that I added to another question:
node-jose explanation / example?
I used node-jose in a research proof, for a reflection of my c# code, I only created signed and Encrypted tokens for decryption and verification, on my server ( written in c#).
I need to use symetric secret key or asymetric public private key pair
?
I used RSA keys for Asymmetric signatures and key wrapping the Symmetric encryption details of the content. The Encryption algorithm for content encryption is a Symmetric one. The node-jose package generated the Symmetric key. The Key Wrap algorithm encrypted the Symmetric key.
The C# code I have decrypts and validates the token signature. Please note: I used the functions of the package to do all the work.
Here are my runkit notebooks for my workups:
for signing (JWS) https://runkit.com/archeon2/5bd66a8e7ee3b70012ec2e39
for encrypting (JWE) https://runkit.com/archeon2/5bd6736ff36b39001313262a
In my final, I combined the two, creating a signed token, then used the output as the payload for the encrypted one (JWS + JWE). I was successful using the c# server code in decrypting, and validating the created tokens.
JWS + JWE : https://runkit.com/archeon2/jws-jwe-integration
How i need to generate and where i need to store keys in my server
node app to then allow me to sign and verify my tokens ?
var store = jose.JWK.createKeyStore();
await store.generate("RSA",2048,{alg:"RS256", key_ops:["sign", "decrypt", "unwrap"]});
lkey = (await store.get());
var key = lkey.toJSON(); //get public key to exchange
key.use = "sig";
key.key_ops=["encrypt","verify", "wrap"];
var pubKey = await jose.JWK.asKey(key);
key = null;
The Keystore can be serialized to JSON, so my concept would be to store this in Session Storage, or Local storage in a browser. Then retrieve the JSON representation and read in the Keystore.
var store= await jose.JWK.asKeyStore({"keys":[{"kty":"RSA","kid":"h9VHWShTfENF6xwjF3FR_b-9k1MvBvl3gnWnthV0Slk","alg":"RS256","key_ops":["sign","decrypt","unwrap"],"e":"AQAB","n":"l61fUp2hM3QxbFKk182yI5wTtiVS-g4ZxB4SXiY70sn23TalKT_01bgFElICexBXYVBwEndp6Gq60fCbaBeqTEyRvVbIlPlelCIhtYtL32iHvkkh2cXUgrQOscLGBm-8aWVtZE3HrtO-lu23qAoV7cGDU0UkX9z2QgQVmvT0JYxFsxHEYuWBOiWSGcBCgH10GWj40QBryhCPVtkqxBE3CCi9qjMFRaDqUg6kLqY8f0jtpY9ebgYWOmc1m_ujh7K6EDdsdn3D_QHfwtXtPi0ydEWu7pj1vq5AqacOd7AQzs4sWaTmMrpD9Ux43SVHbXK0UUkN5z3hcy6utysiBjqOwQ","d":"AVCHWvfyxbdkFkRBGX225Ygcw59fMLuejYyVLCu4qQMHGLO4irr7LD8EDDyZuOdTWoyP7BkM2e7S367uKeDKoQ6o1LND2cavgykokaI7bhxB0OxhVrnYNanJ1tCRVszxHRi78fqamHFNXZGB3fr4Za8frEEVJ5-KotfWOBmXZBvnoXbYbFXsKuaGo121AUCcEzFCGwuft75kPawzNjcdKhItfFrYh45OQLIO08W0fr_ByhxzWMU7yFUCELHSX5-4GT8ssq1dtvVgY2G14PbT67aYWJ2V571aSxM8DTwHrnB9tI8btbkXWt9JyVoQq13wDdo5fVN-c_5t07HBIaPoAQ","p":"8nLGa9_bRnke1w4paNCMjpdJ--eOUpZYbqEa8jnbsiaSWFwxZiOzUakIcpJ3iO0Bl28JEcdVbo7DE7mZ4M3BkOtm577cNuuK8243L7-k1a71X_ko2mQ3yF4rG2PzWAH_5P4wca1uk0Jj3PmhbkXDI6f_btm1X7Vw_U1K6jRhNbE","q":"oCe94Bed1Wzh-xgNq0hz52Z6WLf9eQlNxLzBbYkpLc_bGj9vMeGNO10qdxhWPi8ClkW9h5gBiFEk2s6aEWYRvIoZjrMYXD7xzyTNC5zcsikjNhM3FVj-kVdqUJy25o9uqgn2IwTvQr5WSKuxz37ZSnItEqK5SEgpCpjwEju_XhE","dp":"jAe2ir-0ijOSmGtZh2xMgl7nIFNRZGnpkZwDUDwSpAabJ-W3smKUQ2n5sxLdb3xUGv7KojYbJcvW6CGeurScQ_NycA9QaXgJvSe_QBjUP4bZuiDSc7DGdzfMdfl4pzAgeEZH_KBK6UrDGvIjRumMF6AEbCXaF_lX1TU7O6IdM0E","dq":"fDU2OjS2sQ5n2IAYIc3oLf-5RVM0nwlLKhil_xiQOjppF9s4lrvx96dSxti2EjYNUJQ34JBQJ_OenJ_8tx-tA8cq-RQHAYvDp75H1AjM1NO4vjh60PCbRgdAqdJQu1FkJzXgkdpC4UWSz3txRJaBWQ5hzIEtJ1Tnl5NzJQD3crE","qi":"3EoKqhKh5mwVGldSjwUGX7xnfQIfkQ4IETsQZh9jcfOFlf9f8rT2qnJ7eeJoXWlm5jwMnsTZAMg4l3rUlbYmCdg10zGA5PDadnRoCnSgMBF87d0mVYXxM1p2C-JmLJjqKhJObr3wndhvBXUImo_jV6aHismwkUjc1gSx_b3ajyU"},{"kty":"RSA","kid":"h9VHWShTfENF6xwjF3FR_b-9k1MvBvl3gnWnthV0Slk","use":"verify","alg":"RS256","key_ops":["encrypt","verify","wrap"],"e":"AQAB","n":"l61fUp2hM3QxbFKk182yI5wTtiVS-g4ZxB4SXiY70sn23TalKT_01bgFElICexBXYVBwEndp6Gq60fCbaBeqTEyRvVbIlPlelCIhtYtL32iHvkkh2cXUgrQOscLGBm-8aWVtZE3HrtO-lu23qAoV7cGDU0UkX9z2QgQVmvT0JYxFsxHEYuWBOiWSGcBCgH10GWj40QBryhCPVtkqxBE3CCi9qjMFRaDqUg6kLqY8f0jtpY9ebgYWOmc1m_ujh7K6EDdsdn3D_QHfwtXtPi0ydEWu7pj1vq5AqacOd7AQzs4sWaTmMrpD9Ux43SVHbXK0UUkN5z3hcy6utysiBjqOwQ","use":"sig"}]});
How can i know which one use between OCT, EC, RSA etc ?
For this, the need your token serves may dictate this. I needed the receiver to be the one who could see the contents, so I chose RSA, for Asymmetric keys. Forgery is a bit harder.
These notebooks are somewhat a work in progress. Please review with care, as this is my interpretation and how I worked out what I needed. My hope is that they give some guidance.

Related

Trying to symmetrically encrypt a value for storage in the client (httpOnly cookie) and having an issue decrypting

I am trying to encrypt a value on my server with a private key to store it on the client within an httpOnly cookie.
I am having trouble with the encryption/decryption lifecycle
function encrypt(input) {
const encryptedData = crypto.privateEncrypt(
privateKey,
Buffer.from(input)
)
return encryptedData.toString('base64')
}
function decrypt(input) {
const decryptedData = crypto.privateDecrypt(
{ key: privateKey },
Buffer.from(input, 'base64'),
)
return decryptedData.toString()
}
const enc = encrypt('something moderately secret')
const dec = decrypt(enc)
console.log(dec) // 'something moderately secret'
However the crypto.privateDecrypt function is throwing with
Error: error:04099079:rsa routines:RSA_padding_check_PKCS1_OAEP_mgf1:oaep decoding error
Side question, is it safe to reuse the same private key the server uses to sign JWTs. It's an rsa key generated using ssh-keygen -t rsa -b 4096 -m PEM -f RS256.key
So, you don't use crypto.privateEncrypt() with crypto.privateDecrypt(). That's not how they work. Those functions are for asymmetric encryption, not for symmetric encryption. You use either of these two pairs:
crypto.publicEncrypt() ==> crypto.privateDescrypt()
crypto.privateEncrypt() ==> crypto.publicDecrypt()
So, that's why you're getting the error you're getting. The nodejs doc for crypto.privateDecript() says this:
Decrypts buffer with privateKey. buffer was previously encrypted using the corresponding public key, for example using crypto.publicEncrypt().
If what you really want is symmetric encryption, there are a bunch of options in the crypto module for that. There are some examples shown here: https://www.section.io/engineering-education/data-encryption-and-decryption-in-node-js-using-crypto/ and https://fireship.io/lessons/node-crypto-examples/#symmetric-encryption-in-nodejs.

PDFNet Digital Signature in Node JS using Google KMS

I've seen example of signing https://www.pdftron.com/documentation/nodejs/guides/features/signature/sign-pdf
signOnNextSave uses PKCS #12 certificate, but I use Google KMS for asymmetric signing to keep private keys safe.
Here is example of signing and verifying by Google Cloud KMS
I tried to implement custom SignatureHandler but Node.JS API is different from Java or .NET
https://www.pdftron.com/api/pdfnet-node/PDFNet.SignatureHandler.html
How can I implement custom signing and verifying logic?
const data = Buffer.from('pdf data')
// We have 2048 Bit RSA - PSS Padding - SHA256 Digest key in Google Cloud KMS
const signAsymmetric = async () => {
const hash = crypto.createHash('sha256')
hash.update(data)
const digest = hash.digest()
const digestCrc32c = crc32c.calculate(digest)
// Sign the data with Cloud KMS
const [signResponse] = await client.asymmetricSign({
name: locationName,
digest: {
sha256: digest
},
digestCrc32c: {
value: digestCrc32c
}
})
if (signResponse.name !== locationName) {
throw new Error('AsymmetricSign: request corrupted in-transit')
}
if (!signResponse.verifiedDigestCrc32c) {
throw new Error('AsymmetricSign: request corrupted in-transit')
}
if (
crc32c.calculate(signResponse.signature) !==
Number(signResponse.signatureCrc32c.value)
) {
throw new Error('AsymmetricSign: response corrupted in-transit')
}
// Returns signature which is buffer
const encoded = signResponse.signature.toString('base64')
console.log(`Signature: ${encoded}`)
return signResponse.signature
}
// Verify data with public key
const verifyAsymmetricSignatureRsa = async () => {
const signatureBuffer = await signAsymmetric()
const publicKeyPem = await getPublicKey()
const verify = crypto.createVerify('sha256')
verify.update(data)
verify.end()
const key = {
key: publicKeyPem,
padding: crypto.constants.RSA_PKCS1_PSS_PADDING
}
// Verify the signature using the public key
const verified = verify.verify(key, signatureBuffer)
return verified
}
At this time, the PDFTron SDK only supports custom handlers on C++, Java, and C# (there are more plans to include additional languages in the future).
On a different platform like C++, you would extend the custom handler functions by putting hash.update(data) into SignatureHandler::AppendData, and the rest of signAsymmetric would go into SignatureHandler::CreateSignature. A name would be given to the custom handler for interoperability like Adobe.PPKLite (we do not yet support custom handler SubFilter entries, only Filter -- see PDF standard for the difference -- but this won't matter so long as you use a verification tool that supports Filter Adobe.PPKLite). Please see the following link for a concrete example:
https://www.pdftron.com/documentation/samples/cpp/DigitalSignaturesTest
As for verification, our code can already do this for you if your signatures fulfill the following conditions:
they use a standard digest algorithm
they use RSA to sign
they use the correct data formats according to the PDF standard (i.e. detached CMS, digital signature dictionary)
If you have more questions or require more details, please feel free to reach out to PDFTron support at support#pdftron.com

Decrypting JWE token in golang

I have this problem, I created a JWE in node.js using node-jose by this way:
const keystore = [
{
kty: 'oct',
kid: 'QLdRkgyMx_po0fPo5XnOzQQB4iTcyay36m_PA62SBiw',
k: 'A-OAikjssQZeLkj8N_2Xb9qPBG6lSq10YeLbiTF-kQuM_qKy08jwFqQwsLzn9fmNPkayM9uRg1lHBrPoK_fGtQ'
}
]
const ks = await jose.JWK.asKeyStore(keystore);
const rawKey = ks.get(keystore[0].kid)
const key = await jose.JWK.asKey(rawKey);
const jwe = await jose.JWE
.createEncrypt({format: 'compact'}, key)
.update(payload)
.final();
According to the documentation it is created with "alg": "PBES2-HS256+A128KW", "enc": "A128CBC-HS256", and if I check it in jwt.io, it is.
Then, I need to decrypt in golang, so I do like this using go-jose.v2:
package main
import (
"fmt"
"gopkg.in/square/go-jose.v2"
)
const jweRaw string = "eyJhbGciOiJQQkVTMi1IUzI1NitBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2Iiwia2lkIjoiUUxkUmtneU14X3BvMGZQbzVYbk96UVFCNGlUY3lheTM2bV9QQTYyU0JpdyIsInAyYyI6ODE5MiwicDJzIjoiaVktZEdKaWtYbUZCdXMwRFp5eHdIQSJ9.QkuIGmPojLDX-wpTVTjZRnA093fJRVM6OHkpmoQeyLubahOABg62WQ.z6dm86nWHcWgzmPXiuk0kg.7mOgYF6d9hgfXtTj9RUv7BNuYH-jBAs8px0boOFj1mke_JPetIT44yY7ceffFRfS2QYc6RQMtTvb7vdMArkqeB483g3-tcoCGWxafOb0VfVQHrPTdjpGMLF-9uIJw9z5.RA0Dn-B_Y3kvXYRvVTiNFQ"
const kid string = "QLdRkgyMx_po0fPo5XnOzQQB4iTcyay36m_PA62SBiw"
const k string = "A-OAikjssQZeLkj8N_2Xb9qPBG6lSq10YeLbiTF-kQuM_qKy08jwFqQwsLzn9fmNPkayM9uRg1lHBrPoK_fGtQ"
func main() {
jwe, err1 := jose.ParseEncrypted(jweRaw)
if err1 != nil {
panic(err1)
}
fmt.Println("jwe", jwe)
bytes, err2 := jwe.Decrypt(jose.JSONWebKey{Algorithm: "PBES2-HS256+A128KW", Use: "A128CBC-HS256", KeyID: kid, Key: k})
if err2 != nil {
panic(err2)
}
fmt.Println("bytes", string(bytes))
}
But it panics "panic: square/go-jose: error in cryptographic primitive"
You can check it here: https://play.golang.org/p/qB3QNtGwBsK
I already tried with https://github.com/lestrrat-go/jwx but, it doesn't support PBES2-HS256+A128KW algorithm
Thanks.
UPDATE: here's more information:
They key in node was created with this:
const keystore = await jose.JWK.createKeyStore()
const key = await a.generate('oct', 512)
console.log(key.toJSON(true))
Then the output was saved in this array:
const keystore = [
{
kty: 'oct',
kid: 'QLdRkgyMx_po0fPo5XnOzQQB4iTcyay36m_PA62SBiw',
k: 'A-OAikjssQZeLkj8N_2Xb9qPBG6lSq10YeLbiTF-kQuM_qKy08jwFqQwsLzn9fmNPkayM9uRg1lHBrPoK_fGtQ'
}
]
I've been trying create the same JWE with the same JWK in golang and I can decrypt in golang, but neither in node (I got a "key not found" error)... So, cross decrypting doesn't work for me. What am I doing wrong?
k is a base64url encoded representation of the octet key, unless the go interface specifically mentions passing keys in JWK format, which it doesn't, you need to provide the raw key. base64url.decode() the k to get the raw key bytes.
Also, as a sidenote, PBES2-HS256+A128KW is intended to be used with passwords, not keys, given it's computationally heavy i'd recommend a different key wrapping algorithm (not a symmetric passphrase based one). You can use asymmetric crypto to encrypt for a recipient. And if you also want to achieve authentication of the message, don't use key wrapping at all, use the Direct Key Agreement from JWE instead.

How to properly implement AES encryption with .net core 2?

For some reason, I've been asked to implement some basic encryption to secure a specific value transmitted to the client (depending on the client).
Context is: we are the one who generate the encrypted key, we pass that encrypted key to the client, and the client will never have to decrypt it (but we will have to in backend)
Example => we give the encrypted key "123ABCDE==" to the client. The client calls our API passing data + that encrypted key, like:
{
"encKey": "123ABCDE==",
"payload": "somedatahere"
}
Then we decrypt the key, if it matches a specific value in DB (again, depending on client), we continue with some other operations.
So, I decided to go with AES encryption. Following is what I have for now.
definition of the key information:
public class KeyInfo
{
public byte[] Key { get; }
public byte[] Iv { get; }
public KeyInfo()
{
using (var myAes = Aes.Create())
{
Key = myAes.Key;
Iv = myAes.IV;
}
}
public KeyInfo(string key, string iv)
{
Key = Convert.FromBase64String(key);
Iv = Convert.FromBase64String(iv);
}
}
the encryption method
private static byte[] Encrypt_AES(string plainText, byte[] key, byte[] iv)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException(nameof(plainText));
if (key == null || key.Length <= 0)
throw new ArgumentNullException(nameof(key));
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException(nameof(iv));
byte[] encrypted;
using (var aesAlgo = Aes.Create())
{
aesAlgo.Key = key;
aesAlgo.IV = iv;
var encryptor = aesAlgo.CreateEncryptor(aesAlgo.Key, aesAlgo.IV);
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
the decryption method:
private static string Decrypt_AES(byte[] cipherText, byte[] key, byte[] iv)
{
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException(nameof(cipherText));
if (key == null || key.Length <= 0)
throw new ArgumentNullException(nameof(key));
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException(nameof(iv));
string plaintext;
using (var aesAlgo = Aes.Create())
{
aesAlgo.Key = key;
aesAlgo.IV = iv;
var decryptor = aesAlgo.CreateDecryptor(aesAlgo.Key, aesAlgo.IV);
using (var msDecrypt = new MemoryStream(cipherText))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
the key and IV stored in appsettings.json:
"EncryptionKey": "myEncryptionKeyHere",
"EncryptionInitialVector": "myInitialVectorHere",
the registration in Satrtup.cs
services.AddTransient(ec => new EncryptionService(new KeyInfo(appSettings.EncryptionKey, appSettings.EncryptionInitialVector)));
I have a few question about all of this.
is AES rh right choice for my needs?
is the way it is implemented here correct?
where should I store the Key and IV ? (not sure appsettings.json is okay)
how do I generate the Key and IV ? Is there tools for that?
Thanks for reading!
EDIT:
You say "we are the one who generate the encrypted key, we pass that
encrypted key to the client" - how does that happen securely?
-> The client will have to connect to his account where he could access that encKey.
So, reading #vcsjones answer, AES may not be the right thing to implement here. Since I don't want to store the IV on database, if the client loses it, it means he would have to generate another key, with another IV, and change the encKey in all applications.
Would an asymetric encryption be better? If I understood correctly, it would mean to encrypt the value with a private key, give that encrypted value to the client + the public key (which would be the same for every client?)
is AES the right choice for my needs?
By itself, no it is not. AES is a cryptographic primitive - a building block - and such building blocks are not usually useful by themselves. For example with AES-CBC (the mode you are using), this is currently vulnerable to a padding oracle attack and lacks authentication. AES might be the right choice when combined with other primitives that provide authentication, like an HMAC.
The best way to solve this problem is to treat primitives for what they are - primitives that are insufficient for use on their own. There are other libraries, like libsodium, that are more abstracted concepts of cryptography, and provides simple APIs that "do the right thing".
You say "we are the one who generate the encrypted key, we pass that encrypted key to the client" - how does that happen securely?
Barring using something like libsodium, there are some issues to address.
There is no authentication of the ciphertext ("authentication" in cryptography has its own meaning, not like sign-on authentication).
The initialization vector should never be used more than once with the same key. You appear to be using a fixed IV. Every thing you encrypt should use its own random IV. The IV is not a secret. It should be authenticated however along with the cipher text as per point 1.
where should I store the Key and IV ?
The IV, since there should be a 1:1 of them with each cipher text (encrypted output) should be stored with the cipher text. When it's time to decrypt, the caller will need to provide the IV again.
The Key is the real secret. Storing them securely is important. If you store it in appsettings.json, then the security of your key is the same as the security of that JSON file. A more common approach in a cloud environment is to use a managed service. Azure has Azure Key Vault, AWS has KMS and Secret Manager.
how do I generate the Key and IV ? Is there tools for that?
They should be generated with a CSPRNG. For example, to do so programmatically:
byte[] iv = new byte[128 / 8];
RandomNumberGenerator.Fill(iv);
//iv now contains random bytes
You can do the same for generating a key.

How keep in the secret the RSA - private key in browser - implement Proof of Possession with an Asymmetric Key

I want to implement the Proof of Possession with an Asymmetric Key specs.
I would like to store the RSA in secure place in the browser - I will be able to sign the part of the request with private key and with public key as part of JWT verify the request.
I don't know how import RSA into my browser - where can I store RSA private key secure in browser?
Look at the WebCrypto API and IndexedDB. There are some WebCrypto examples here - https://github.com/diafygi/webcrypto-examples.
This will allow you to import the key in a way that it cannot be extracted - only used to sign and verify signatures. This will however be wiped when browser data is cleared with the "clear application data" (/similar - depends on browser) flag is ticked.
For example to import a key and store it in an IndexedDB (this code hasn't been tested / _openDb would have to be implemented) -
window.crypto.subtle.importKey(
"jwk", //can be "jwk" (public or private), "spki" (public only), or "pkcs8" (private only)
{ //this is an example jwk key, other key types are Uint8Array objects
kty: "RSA",
e: "AQAB",
n: "vGO3eU16ag9zRkJ4AK8ZUZrjbtp5xWK0LyFMNT8933evJoHeczexMUzSiXaLrEFSyQZortk81zJH3y41MBO_UFDO_X0crAquNrkjZDrf9Scc5-MdxlWU2Jl7Gc4Z18AC9aNibWVmXhgvHYkEoFdLCFG-2Sq-qIyW4KFkjan05IE",
alg: "PS256",
ext: true,
},
{ //these are the algorithm options
name: "RSA-PSS",
hash: {name: "SHA-256"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
},
false, //whether the key is extractable (i.e. can be used in exportKey)
["verify"] //"verify" for public key import, "sign" for private key imports
).then(function(key){
((_db_handle === null) ?
_openDb() :
Promise.resolve()
).then(function() {
let tx = _db_handle.transaction("KeyStore", "readwrite");
let store = tx.objectStore("KeyStore");
let putKey = store.put({id: "Key 1", key: key});
putKey.onsuccess = function() {
resolve();
};
putKey.onerror = function() {
reject(putKey.error);
};
});
})
Then to read it back out -
let tx = _db_handle.transaction("KeyStore", "readwrite");
let store = tx.objectStore("KeyStore");
let getKey = store.get("Key 1");
getKey.onsuccess = function() {
resolve(getKey.result ? getKey.result.key : null);
};
getKey.onerror = function() {
reject(getKey.error);
};
Maybe you can create an extension for holding keys. Consider that if you need to store private keys in a browser, you should only allow to store encrypted keys per default and in addition if you want/need to store more keys don't allow the same password on different key files.
Also consider using a master key and/or OTPs to decrypt the store.
Looking for an extension where these things are available could save some work

Resources