Question is for transfer encrypted data between two services (Like HTTP, GRPC or etc...) Can I transfer IV
and AuthTag
in plain, Is this approach secure?
I have sample code in Node.js and I'm not crypto expert. See the code for more info:
const crypto = require('crypto');
class AES {
static encrypt(string, key) {
const iv = Buffer.from(crypto.randomBytes(12), 'utf8');
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
let enc = cipher.update(string, 'utf8', 'base64');
enc += cipher.final('base64');
return [enc.toString('base64'), iv.toString('base64'), cipher.getAuthTag().toString('base64')].join('.');
}
static decrypt(encrypted, key) {
const [encString, ivString, authTagString] = encrypted.split('.');
const enc = Buffer.from(encString, 'base64');
const iv = Buffer.from(ivString, 'base64');
const authTag = Buffer.from(authTagString, 'base64');
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(authTag);
let str = decipher.update(enc, 'base64', 'utf8');
str += decipher.final('utf8');
return str;
}
}
const phrase = 'Sample Text 1234';
// key store in secure place
const key = Buffer.from(crypto.randomBytes(32), 'utf8');
const encrypted = AES.encrypt(phrase, key);
console.log(encrypted) // pass encrypted data into network that include (IV and AuthTag)
// for another
const decrypted = AES.decrypt(encrypted, key);
console.log(decrypted)
console.log(decrypted === phrase)
- Use case, transfer data between service that might work in public network
- Just a Secure key is shared between service nothing more.