cisco / node-jose

Apache License 2.0
701 stars 125 forks source link

Encrypt using a SHA256 value using AESGCM256 and AESGCMKW #269

Open sanjays95 opened 5 years ago

sanjays95 commented 5 years ago

Hi Team,

Is it possible to encrypt using a SHA256 value? I am using AESGCM256 and key wrap using AESGCM256KW. Below is the code

var shared_secret = "this is my shared secret";
var digest = crypto.createHash('sha256').update(shared_secret);
var key = await keystore.add(digest);
var payload = {'foo':'bar'};

var encData = await jose.JWE.createEncrypt({format:'compact',fields:{alg:'A256GCMKW',enc:'A256GCM'}}, key).update(payload).final()

Appreciate the help!

sanjays95 commented 5 years ago

Since the key is not a JWK type. It is failing. How do I convert my digest to a JWK ?

panva commented 5 years ago

How do I convert my digest to a JWK ?

First of all, you're missing .digest() after updating the hash with your shared secret, that's what produces your final digest as a buffer. A jwk for the digest as the secret would like so.

const base64url = require('base64url')

const jwk = {
  kty: 'oct',
  k: base64url.encode(digest)
}

Alternatively, using a node-only library, you can import the digest right away.

const jose = require('jose')
const shared_secret = "this is my shared secret";
const digest = crypto.createHash('sha256').update(shared_secret).digest();

const key = jose.JWK.asKey(digest);
const payload = {'foo':'bar'};
const jwe = jose.JWE.encrypt(JSON.stringify(payload), key, { alg:'A256GCMKW', enc:'A256GCM' })
sanjays95 commented 4 years ago

Hey. Thanks a ton. this helped!! Can I console log the CEK value from AESGCMKW? If yes, can you please shed some light as to how to do this ?