Node.js crypto create ecdh with the tron public address - node.js

I am aiming for wallet address encryption, using the TronWeb.createAccount(), I fetch the public address for wallet in base58 and the private key as hex.
Sample Public Address: TPeGpPdJGQoNobV4SEjXLdrjefN3iCAAAA
Sample Private Key: 6B07B82D50B27171F35BF1DEAB14...
I am getting the keys using following code.
const TronWeb = require('tronweb');
function createAccount() {
try {
const tronWeb = new TronWeb(fullNode, solidityNode, eventServer);
return tronWeb.createAccount();
} catch (error) {
console.log(error);
throw error;
}
}
When I use the getPublicKey() method after setting the private key in bob.createECDH() the code works fine but in actual I will not have the utility of setPrivateKey() method for alice when I am on bob side. So I will have to pass the base58 public address instead of bob.getPublicKey() or alice.getPublicKey() on either side.
const alice_secret = alice.computeSecret('HEX_PUBLIC_KEY','hex');
Following is the full code for encryption and decryption.
const alice = crypto.createECDH('secp256k1');
const bob = crypto.createECDH('secp256k1');
bob.setPrivateKey("PRIVATE_KEY_FOR_BOB", "hex");
alice.setPrivateKey("PRIVATE_KEY_FOR_ALICE", "hex");
const alice_secret = alice.computeSecret(bob.getPublicKey());
console.log("alice's shared Key: " + alice_secret.toString('hex') + "\n");
var algo = 'aes-256-ecb', plainText = "Some secret to share bob";
var cipher = crypto.createCipher(algo, alice_secret)
var encrypted = cipher.update(plainText, 'utf8', 'hex')
encrypted += cipher.final('hex');
console.log("Encrypted: " + encrypted);
const bob_secret = bob.computeSecret(alice.getPublicKey());
console.log("bob's shared Key: " + bob_secret.toString('hex') + "\n");
var decipher = crypto.createDecipher(algo, bob_secret)
var decrypted = decipher.update(encrypted, 'hex', 'utf8')
decrypted += decipher.final('utf8');
console.log("Decrypted: " + decrypted);
if (plainText == decrypted) {
console.log("ECDH Success")
}
The output is expected when I use setPrivateKey() and then use getPublicKey()
alice's shared Key: 238c3eba08585a5cae1006710c79fe2de329545e9ca4c1ef719c53b55eb337b6
app.js:21 Encrypted: 44184052d9e205fd855aaf5f30b5f186c4bab88a5cfdce58d99cd8c696954c8dd5676807e6fe372fbe3ca5b230e54293
app.js:29 bob's shared Key: 238c3eba08585a5cae1006710c79fe2de329545e9ca4c1ef719c53b55eb337b6
app.js:35 Decrypted: QmdUuJDvgZ7EWEpJmEcFCoYwotn9CHyvK4qEhZs82AhZoQ
app.js:40 ECDH Success
When I convert the public key to hex using bs58 or any other package it says
UnhandledPromiseRejectionWarning: Error: Failed to translate Buffer to a EC_POINT
Is there a way to convert this public address and use it in this situation?

I had to study the ECDH supported key format and regenerate the keys according to new format to be able to fix this issue.
There were two formats of the public key that we can use to encrypt data.

Related

NOdeJs Rest API response encoded with private key

I have been supplied with a public and private key to call a restAPI in nodejs.
Both keys are in clear ASCII format.
I use the following code to encript my message:
(async () => {
// put keys in backtick (``) to avoid errors caused by spaces or tabs
// ENCRYPT
const publicKeyArmored = fs.readFileSync(publicKeyFile, {
encoding: 'utf8',
flag: 'r'
});
const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
const encrypted = await openpgp.encrypt({
message: await openpgp.createMessage({ text: 'Hello, World!' })
, encryptionKeys: publicKey
// , signingKeys: privateKey // optional
});
console.log("Encrypted:", encrypted); // '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'
}
However when I try to decrypt the response, all the code examples I have found seem to require a passphrase to use the private key supplied, but this is not encoded in any way, it's again plain ascii, begining with :
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG v2.0.22 (GNU/Linux)
lQO+BGHApmABCAC70QG0T3bh1MVRGKmY9cOM2NFEie2KXCLGXUPa+2B5JOnDypGX
msoLau8FtKIqvAVAYSsONlE4P4RcltyrOTHLMvWhu73ZTJIBu6GGkgM6bKOtu2Rp
/VbPylPIXrkA3A4s0089VGgmFqJul04lit2svLwxD31ZEIY3Ke3kd0dV0nM4npRO
EZUPR5Qr6KCwBsL+ZHbDuG2YrC7oKcnJTXcdszrF7+FLAwI8viZhJOXyagJRioXd
/H/IpauXyvejN22/eRjch9IRMSz+qh0avj9tcuuJ1k4sBQQukeoIoPwFe9Rb9TY2 .....
the following code suggests I need a passphrase, but this key does not appear to require one:
async function decrypt() {
const privateKey = (await openpgp.key.readArmored([privateKeyArmored])).keys[0];
await privateKey.decrypt(passphrase);
const encryptedData = fs.readFileSync("encrypted-secrets.txt");
const decrypted = await openpgp.decrypt({
message: await openpgp.message.readArmored(encryptedData),
privateKeys: [privateKey],
});
console.log(decrypted.data);
}
SO how do I use it without a passphrase?
Thank you in advance for your xmas spirit and any help!
Your private key is ASCII armored, so it is possible to transfer it in text representation. After calling gpg --dearmor on it you'll get the binary data. Also private key may be stored using the password encryption, or not encrypted at all (in the second case you will not need to call privateKey.decrypt()). To check this you may use the command gpg --list-packets keyfile.asc.

Nodejs AES-256-GCM decrypt the encrypted client message by webcrypto api

I've Encrypted my text by a key in Client by AES-256-GCM algorithm and I can decrypt it in Client, But when I send it to the Backend which has a SharedKey(the same as the Client has), it can decrypt the message by AES-256-CTR algorithm(I used this algo because the AES-256-GCM in Nodejs needs authTag that I don't create it in Client and iv is the only thing I have).
When I decrypt the message on the Backend side, it works with no error, but the result is not what I encrypted in the Client
Here is what I wrote:
Client:
async function encrypt(text: string) {
const encodedText = new TextEncoder().encode(text);
const aesKey = await generateAesKey();
const iv = window.crypto.getRandomValues(
new Uint8Array(SERVER_ENCRYPTION_IV_LENGTH)
);
const encrypted = await window.crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv,
},
aesKey,
encodedText
);
const concatenatedData = new Uint8Array(
iv.byteLength + encrypted.byteLength
);
concatenatedData.set(iv);
concatenatedData.set(new Uint8Array(encrypted), iv.byteLength);
return arrayBufferToBase64(concatenatedData),
}
Backend:
export function decrypt(sharedKey: string, message: string) {
const messageBuffer = new Uint8Array(base64ToArrayBuffer(message));
const iv = messageBuffer.subarray(0, 16);
const data = messageBuffer.subarray(16);
const decipher = crypto.createDecipheriv(
'aes-256-ctr',
Buffer.from(sharedKey, 'base64'),
iv
);
const decrypted =
decipher.update(data, 'binary', 'hex') + decipher.final('hex');
return Buffer.from(decrypted, 'hex').toString('base64');
}
Sample usage:
const encrypted = encrypt("Hi Everybody");
// send the encrypted message to the server
// Response is: Ô\tp\x8F\x03$\f\x91m\x8B B\x1CkQPQ=\x85\x97\x8AêsÌG0¸Ê
Since GCM is based on CTR, decryption with CTR is in principle also possible. However, this should generally not be done in practice, since it skips the authentication of the ciphertext, which is the added value of GCM over CTR.
The correct way is to decrypt on the NodeJS side with GCM and properly consider the authentication tag.
The authentication tag is automatically appended to the ciphertext by the WebCrypto API, while the crypto module of NodeJS handles ciphertext and tag separately. Therefore, not only the nonce but also the authentication tag must be separated on the NodeJS side.
The following JavaScript/WebCrypto code demonstrates the encryption:
(async () => {
var nonce = crypto.getRandomValues(new Uint8Array(12));
var plaintext = 'The quick brown fox jumps over the lazy dog';
var plaintextEncoded = new TextEncoder().encode(plaintext);
var aesKey = base64ToArrayBuffer('a068Sk+PXECrysAIN+fEGDzMQ3xlpWgE1bWXHVLb0AQ=');
var aesCryptoKey = await crypto.subtle.importKey('raw', aesKey, 'AES-GCM', true, ['encrypt', 'decrypt']);
var ciphertextTag = await crypto.subtle.encrypt({name: 'AES-GCM', iv: nonce}, aesCryptoKey, plaintextEncoded);
ciphertextTag = new Uint8Array(ciphertextTag);
var nonceCiphertextTag = new Uint8Array(nonce.length + ciphertextTag.length);
nonceCiphertextTag.set(nonce);
nonceCiphertextTag.set(ciphertextTag, nonce.length);
nonceCiphertextTag = arrayBufferToBase64(nonceCiphertextTag.buffer);
document.getElementById("nonceCiphertextTag").innerHTML = nonceCiphertextTag; // ihAdhr6595oyQ3koj52cnZp7VeB1fzWuY1v7vqFdSQGxK0VQxIXUegB1mVG4rC5Aymij7bQ9rmnFWbpo7C2znN4ROnnChB0=
})();
// Helper
// https://stackoverflow.com/a/9458996/9014097
function arrayBufferToBase64(buffer){
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
// https://stackoverflow.com/a/21797381/9014097
function base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
<p style="font-family:'Courier New', monospace;" id="nonceCiphertextTag"></p>
This code is basically the same as your code, with some changes needed because of methods you didn't post like generateAesKey() or arrayBufferToBase64().
Example output:
ihAdhr6595oyQ3koj52cnZp7VeB1fzWuY1v7vqFdSQGxK0VQxIXUegB1mVG4rC5Aymij7bQ9rmnFWbpo7C2znN4ROnnChB0=
The following NodeJS/crypto code demonstrates the decryption. Note the tag separation and explicit passing with setAuthTag():
var crypto = require('crypto');
function decrypt(key, nonceCiphertextTag) {
key = Buffer.from(key, 'base64');
nonceCiphertextTag = Buffer.from(nonceCiphertextTag, 'base64');
var nonce = nonceCiphertextTag.slice(0, 12);
var ciphertext = nonceCiphertextTag.slice(12, -16);
var tag = nonceCiphertextTag.slice(-16); // Separate tag!
var decipher = crypto.createDecipheriv('aes-256-gcm', key, nonce);
decipher.setAuthTag(tag); // Set tag!
var decrypted = decipher.update(ciphertext, '', 'utf8') + decipher.final('utf8');
return decrypted;
}
var nonceCiphertextTag = 'ihAdhr6595oyQ3koj52cnZp7VeB1fzWuY1v7vqFdSQGxK0VQxIXUegB1mVG4rC5Aymij7bQ9rmnFWbpo7C2znN4ROnnChB0=';
var key = 'a068Sk+PXECrysAIN+fEGDzMQ3xlpWgE1bWXHVLb0AQ=';
var decrypted = decrypt(key, nonceCiphertextTag);
console.log(decrypted);
Output:
The quick brown fox jumps over the lazy dog
For completeness: Decryption of a GCM ciphertext with CTR is also possible by appending 4 bytes to the 12 bytes nonce (0x00000002). For other nonce sizes the relation is more complex, see e.g. Relationship between AES GCM and AES CTR. However, as already said, this should not be done in practice, since it bypasses the authentication of the ciphertext and is thus insecure.

Nodejs `crypto.publicEncrypt` would not take public key generated by `ssh-keygen rsa`

I used ssh-keygen rsa to generate an RSA keypair. The generated public key looks like this:
ssh-rsa AAAAB3NzaC1yc2EAAA...
When I try to use crypto in Node.js to encrypt a plain string,
const fs = require('fs');
const { publicEncrypt } = require('crypto');
const publicKey = fs.readFileSync('$path/to/publicKey').toString();
const encryptedToken = publicEncrypt(publicKey, Buffer.from('some plain string'));
it would give out the following error:
Error: error:0909006C:PEM routines:get_name:no start line
at node:internal/crypto/cipher:78:12
...
library: 'PEM routines',
function: 'get_name',
reason: 'no start line',
code: 'ERR_OSSL_PEM_NO_START_LINE'
I am pretty new to cryptography and know only the general idea of public/private key encryption so would really appreciate any advice.
Edit:
I understand that crypto comes with method to generate key pairs, so I guess the question is more about why the ssh-rsa public key did not work here.
The posted public key is in OpenSSH format, which is not supported by NodeJS's crypto module, see documentation of crypto.publicEncrypt(key, buffer).
However, keys in OpenSSH format can be converted to formats that can be processed by NodeJS. This can be done via tools, e.g. ssh-keygen, or via libraries, e.g. node-sshpk.
Alternatively, keys can be generated directly in the required format using OpenSSL.
The following example uses the node-sshpk library and converts an OpenSSH private key to a PEM encoded PKCS8 key and an OpenSSH public key to a PEM encoded X.509/SPKI key. Both target formats are supported by NodeJS:
var sshpk = require('sshpk');
var crypto = require('crypto');
var privateKeyOpenSSH = `-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn
NhAAAAAwEAAQAAAQEApcFmUiObzYdRrKivbYrUwJ8plRfjcgA1nXIHpMKj4q0l4vatprYe
vNS2l06y2Qvz1Txu7AeS9+zT673zczwvLgENcZb6lXA576XMLjcmZhnNKXDRnRV/UCMlea
jdwdhQ93YJpsGRCUewD8k6IOO6G/MVAQ433ybBuCPJysTLWNk2Vv/J3VrLkBWGLiwOUcnZ
pR17/mm6QBOsLRAuBs1jELcid1Jdpc8wfULlrSdCfw/P2mXOqpuTMhSEBy4yE+W6V54MSI
Vw4BaxlrcAmC/Rh7OHJrhuIEmmOStqmMPe7HvFKNTjqzISAiyWmPWWwI9UuP4g7b0p7GAk
0YMevLPQnwAAA9jLWAaqy1gGqgAAAAdzc2gtcnNhAAABAQClwWZSI5vNh1GsqK9titTAny
mVF+NyADWdcgekwqPirSXi9q2mth681LaXTrLZC/PVPG7sB5L37NPrvfNzPC8uAQ1xlvqV
cDnvpcwuNyZmGc0pcNGdFX9QIyV5qN3B2FD3dgmmwZEJR7APyTog47ob8xUBDjffJsG4I8
nKxMtY2TZW/8ndWsuQFYYuLA5RydmlHXv+abpAE6wtEC4GzWMQtyJ3Ul2lzzB9QuWtJ0J/
D8/aZc6qm5MyFIQHLjIT5bpXngxIhXDgFrGWtwCYL9GHs4cmuG4gSaY5K2qYw97se8Uo1O
OrMhICLJaY9ZbAj1S4/iDtvSnsYCTRgx68s9CfAAAAAwEAAQAAAQAstgRxt6U5RX0kg8P+
WmqVItnGm9EAWUodFDs3mEE4zdfgZwXkaE/WQ9KU8eeQYIb/R/PruwdL1Rg9CNn4hY18bV
BBCabCVKlsGV8AQGQdOmx69zGzm67h4Pkk3gYjWcRNXAuybZg/1pSJTZBees8i5ukNhdZQ
XVX347908KyhZFb4jlYws7gbOkVBP7ludHSnnrodL91F2ouKrgplLfWu40sgU3fSpSybby
3Llt+FUW6UjCErp54c2LS5vZtvTJK+wVr2fYF4Y1Sgmv+JZ4bJUkZgaxzcHoOLF5GfuQFo
dvJVxbSXPUhk7JW7ur9hHLkEaJtYf0xf1TwJdPRQxu3xAAAAgQCui5wvYjZrCM9wWDXpWh
1dNGPIJQuX8aCxi2tfTkRYlkPUWFSYd+orQr53/FPTxLdwe9lAe8x0Xkr+wMga6771ywHw
sT6xk7nCabXcN6PQCn5DjYMtLPfa5rY3+yHR01pVSzo9l6JcvangU1xyw7MRYj0LGZVSbp
U/beRO/bXekQAAAIEA0uUTVG9wPiqZRTLT6H8rQ4ZK96VcTF+CnmJUO+3Fsp/D7jfYItZF
2GcqzWYv6tsvumdhZt0dziXBy7fAJDW88k/nq+BNTlDXEYzkEA+x13eaLAzfI08SwlAnF5
zxZUo8yIsjKtyt9gs1+VVgtwpvvqUVDUibjbWxaE4OWtdLjwUAAACBAMk02gcYkJylXw12
4me1vtWpw7/7pga3eK0Y4ZTZgpCZXhrLnl9yWXrVIlvV8dLJQI88s7+1CRU9HPi+2BGtgI
mJ5crYws7q0QgLODg1rDosd4vkkKok5XPUsrKDLxwme+Ipq26IdRyoJF2ZiRHvPG5ajjmK
gWByjcdktmXM+UpTAAAAHHRmbG9yZXNfZHQwMUB0ZmxvcmVzX2R0MDEtUEMBAgMEBQY=
-----END OPENSSH PRIVATE KEY-----`
var publicKeyOpenSSH = `ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQClwWZSI5vNh1GsqK9titTAnymVF+NyADWdcgekwqPirSXi9q2mth681LaXTrLZC/PVPG7sB5L37NPrvfNzPC8uAQ1xlvqVcDnvpcwuNyZmGc0pcNGdFX9QIyV5qN3B2FD3dgmmwZEJR7APyTog47ob8xUBDjffJsG4I8nKxMtY2TZW/8ndWsuQFYYuLA5RydmlHXv+abpAE6wtEC4GzWMQtyJ3Ul2lzzB9QuWtJ0J/D8/aZc6qm5MyFIQHLjIT5bpXngxIhXDgFrGWtwCYL9GHs4cmuG4gSaY5K2qYw97se8Uo1OOrMhICLJaY9ZbAj1S4/iDtvSnsYCTRgx68s9Cf whatever`;
// Convert
var privateKey = sshpk.parsePrivateKey(privateKeyOpenSSH, 'ssh');
var publicKey = sshpk.parseKey(publicKeyOpenSSH, 'ssh');
var privateKeyPkcs8 = privateKey.toBuffer('pkcs8');
var publicKeyX509 = publicKey.toBuffer('pkcs8');
console.log(privateKey.toString('ssh'));
console.log(publicKey.toString('ssh'));
console.log(privateKeyPkcs8.toString('utf8')); // -----BEGIN PRIVATE KEY-----...
console.log(publicKeyX509.toString('utf8')); // -----BEGIN PUBLIC KEY-----...
// Encrypt/Decrypt
var plaintext = Buffer.from('The quick brown fox jumps over the lazy dog', 'utf8');
var ciphertext = crypto.publicEncrypt(publicKeyX509.toString('utf8'), plaintext);
var decryptedText = crypto.privateDecrypt(privateKeyPkcs8.toString('utf8'), ciphertext);
console.log('Ciphertext, base64 encoded: ', ciphertext.toString('base64'));
console.log('Decrypted text: ', decryptedText.toString('utf8'));
const {NodeSSH} = require('node-ssh')
ssh = new NodeSSH()
var sshpk = require('sshpk');
var crypto = require('crypto');
var privateKeyOpenSSH = `private key ecdsa `
var publicKeyOpenSSH = `public key ecdsa`;
// Convert
var privateKey = sshpk.parsePrivateKey(privateKeyOpenSSH, 'ssh');
var publicKey = sshpk.parseKey(publicKeyOpenSSH, 'ssh');
var privateKeyPkcs8 = privateKey.toBuffer('pkcs8');
var publicKeyX509 = publicKey.toBuffer('pkcs8');
ssh.connect({
host: process.env.SSH_host,
username: process.env.SSH_user,
privateKey: Buffer.from('C:/Users/aniru/.ssh/id_ecdsa'),
passphrase:'passphrase string'
})
.then(() => {
console.log("ssh connected");
ssh.execCommand("redis-cli ping", { cwd: "/var/www" }).then((result) =>
{
console.log("STDOUT: " + result.stdout);
console.log("STDERR: " + result.stderr);
});
});

Nodejs elliptic verification wrong

I have created some data to encrypt to make sure that the data can't be modified. Using elliptic I created the data then sign it. Then I modify the data. When I verify the data integrity using the generated signature, it returns true.
Am I confused about the use of elliptic?
Here is the code:
const EC = require("elliptic").ec
const ec = new EC("secp256k1")
class Wallet {
constructor(data, pubKey) {
this.keyPair = ec.genKeyPair();
if (typeof (pubKey) !== "undefined")
this.publicKey = pubKey
else
this.publicKey = this.keyPair.getPublic().encode("hex")
this.data = data
this.creationDate = Date.now()
}
toString() {
console.log("public key: " + this.publicKey)
}
sign() {
let raw = this.publicKey + this.data + this.creationDate;
console.log("signing data: " + raw)
return this.keyPair.sign(raw)
}
static verify(wallet, signature) {
let raw = wallet.publicKey + wallet.data + wallet.creationDate;
console.log("verifying data: " + raw)
return ec.keyFromPublic(wallet.publicKey, "hex").verify(raw, signature)
}
}
module.exports = Wallet
The index file:
const Wallet = require("./Wallet")
let wallet = new Wallet("hello");
wallet.toString()
let signature = wallet.sign()
console.log("\n\nSignature: "+JSON.stringify(signature)+"\n\n")
wallet.data = "world"
console.log("wallet data: "+ wallet.data)
console.log("Verify: "+ (Wallet.verify(wallet, signature)))
console.log("\n\n---------------Another wallet hacking-------------\n\n")
let wallet2 = new Wallet("bar", wallet.publicKey);
wallet2.toString()
let signature2 = wallet2.sign()
console.log("\n\nSignature: "+JSON.stringify(signature)+"\n\n")
console.log("wallet data: "+ wallet2.data)
console.log("Verify: "+ (Wallet.verify(wallet2, signature)))
The output:
public key: 045f349291f48e979d5895dedd523ceadf5f60b8b7e87706565f45d73561b1ba4e836ff6d7f27283cb0fece3a7b08abf37db995eae49666314f5b01954e21958fc
signing data: 045f349291f48e979d5895dedd523ceadf5f60b8b7e87706565f45d73561b1ba4e836ff6d7f27283cb0fece3a7b08abf37db995eae49666314f5b01954e21958fchello1604430087928
Signature: {"r":"9ed97af6f4f3becdfa910c91d4865b9c8d9a317ac47b4b7edbd5d4873ca3b3c3","s":"46e76b801de77ee596a7726b08b1db0cdbd9a6b0404bee7c49be0fccee85e99f","recoveryParam":0}
wallet data: world
verifying data: 045f349291f48e979d5895dedd523ceadf5f60b8b7e87706565f45d73561b1ba4e836ff6d7f27283cb0fece3a7b08abf37db995eae49666314f5b01954e21958fcworld1604430087928
Verify: true
---------------Another wallet hacking-------------
public key: 045f349291f48e979d5895dedd523ceadf5f60b8b7e87706565f45d73561b1ba4e836ff6d7f27283cb0fece3a7b08abf37db995eae49666314f5b01954e21958fc
signing data: 045f349291f48e979d5895dedd523ceadf5f60b8b7e87706565f45d73561b1ba4e836ff6d7f27283cb0fece3a7b08abf37db995eae49666314f5b01954e21958fcbar1604430087974
Signature: {"r":"9ed97af6f4f3becdfa910c91d4865b9c8d9a317ac47b4b7edbd5d4873ca3b3c3","s":"46e76b801de77ee596a7726b08b1db0cdbd9a6b0404bee7c49be0fccee85e99f","recoveryParam":0}
wallet data: bar
verifying data: 045f349291f48e979d5895dedd523ceadf5f60b8b7e87706565f45d73561b1ba4e836ff6d7f27283cb0fece3a7b08abf37db995eae49666314f5b01954e21958fcbar1604430087974
Verify: true
Thanks to the #Topaco answer. I understand elliptic does not sign any kind of content. I also cast the string to an array and elliptic still sign and verify the content wrongly.
It considered
["0","4","3","7","d","0","6","2","d","a","a","7","a","9","5","3","f","a","5","6","5","9","3","2","3","d","d","d","0","7","6","4","e","b","8","a","2","e","9","1","9","6","b","4","d","1","f","6","c","1","8","5","0","9","3","5","a","6","0","b","9","a","6","1","5","6","4","d","1","8","a","5","9","c","b","d","e","2","8","f","6","1","9","5","7","1","0","1","c","4","2","f","b","1","2","b","b","4","2","4","1","3","a","4","3","e","e","4","3","6","8","8","f","1","9","d","a","3","6","f","c","9","1","c","6","1","9","9","6","7","h","e","l","l","o","1","6","0","4","4","4","7","6","8","8","9","2","8"]
the same as
["0","4","3","7","d","0","6","2","d","a","a","7","a","9","5","3","f","a","5","6","5","9","3","2","3","d","d","d","0","7","6","4","e","b","8","a","2","e","9","1","9","6","b","4","d","1","f","6","c","1","8","5","0","9","3","5","a","6","0","b","9","a","6","1","5","6","4","d","1","8","a","5","9","c","b","d","e","2","8","f","6","1","9","5","7","1","0","1","c","4","2","f","b","1","2","b","b","4","2","4","1","3","a","4","3","e","e","4","3","6","8","8","f","1","9","d","a","3","6","f","c","9","1","c","6","1","9","9","6","7","w","o","r","l","d","1","6","0","4","4","4","7","6","8","8","9","2","8"]
The first one contains hello and the second one contains world.
I fixed it by passing a sha256 encoded string to sign and to verify.
I installed the package crypto-js then I encode the string:
const Sha256 = require("crypto-js/sha256")
// Signing
const encContent = Sha256(raw).toString()
this.keyPair.sign(encContent )
// Verifying
const encContent = Sha256(raw).toString()
ec.keyFromPublic(wallet.publicKey, "hex").verify(encContent , signature)

"Unsupported state or unable to authenticate data" with aes-128-gcm in Node

I'm trying to implement encrypt/decrypt functions using aes-128-gcm as provided by node crypto. From my understanding, gcm encrypts the ciphertext but also hashes it and provides this as an 'authentication tag'. However, I keep getting the error: "Unsupported state or unable to authenticate data".
I'm not sure if this is an error in my code - looking at the encrypted ciphertext and auth tag, the one being fetched by the decrypt function is the same as the one produced by the encrypt function.
function encrypt(plaintext) {
// IV is being generated for each encryption
var iv = crypto.randomBytes(12),
cipher = crypto.createCipheriv(aes,key,iv),
encryptedData = cipher.update(plaintext),
tag;
// Cipher.final has been called, so no more encryption/updates can take place
encryptedData += cipher.final();
// Auth tag must be generated after cipher.final()
tag = cipher.getAuthTag();
return encryptedData + "$$" + tag.toString('hex') + "$$" + iv.toString('hex');
}
function decrypt(ciphertext) {
var cipherSplit = ciphertext.split("$$"),
text = cipherSplit[0],
tag = Buffer.from(cipherSplit[1], 'hex'),
iv = Buffer.from(cipherSplit[2], 'hex'),
decipher = crypto.createDecipheriv(aes,key,iv);
decipher.setAuthTag(tag);
var decryptedData = decipher.update(text);
decryptedData += decipher.final();
}
The error is being thrown by decipher.final().
In case if someone still tries to get a working example of encryption and decryption process.
I've left some comments that should be taken into consideration.
import * as crypto from 'crypto';
const textToEncode = 'some secret text'; // utf-8
const algo = 'aes-128-gcm';
// Key bytes length depends on algorithm being used:
// 'aes-128-gcm' = 16 bytes
// 'aes-192-gcm' = 24 bytes
// 'aes-256-gcm' = 32 bytes
const key = crypto.randomBytes(16);
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algo, key, iv);
const encrypted = Buffer.concat([
cipher.update(Buffer.from(textToEncode, 'utf-8')),
cipher.final(),
]);
const authTag = cipher.getAuthTag();
console.info('Value encrypted', {
valueToEncrypt: textToEncode,
encryptedValue: encrypted.toString('hex'),
authTag: authTag.toString('hex'),
});
// It's important to use the same authTag and IV that were used during encoding
const decipher = crypto.createDecipheriv(algo, key, iv);
decipher.setAuthTag(authTag);
const decrypted = Buffer.concat([
decipher.update(encrypted),
decipher.final(),
]);
console.info('Value decrypted', {
valueToDecrypt: encrypted.toString('hex'),
decryptedValue: decrypted.toString('utf-8'),
});
I managed to fix this: the issue was that I wasn't specifying an encoding type for cipher.final() and I was returning it within a String, so it wasn't returning a Buffer object, which decipher.final() was expecting.
To fix, I add 'utf-8' to 'hex' encoding parameters within my cipher.update and cipher.final, and vice versa in decipher.
Edited to add code example - note this is from 2018, so may be outdated now.
function encrypt(plaintext) {
// IV is being generated for each encryption
var iv = crypto.randomBytes(12),
cipher = crypto.createCipheriv(aes,key,iv),
encryptedData = cipher.update(plaintext, 'utf-8', 'hex'),
tag;
// Cipher.final has been called, so no more encryption/updates can take place
encryptedData += cipher.final('hex');
// Auth tag must be generated after cipher.final()
tag = cipher.getAuthTag();
return encryptedData + "$$" + tag.toString('hex') + "$$" + iv.toString('hex');
}
function decrypt(ciphertext) {
var cipherSplit = ciphertext.split("$$"),
text = cipherSplit[0],
tag = Buffer.from(cipherSplit[1], 'hex'),
iv = Buffer.from(cipherSplit[2], 'hex'),
decipher = crypto.createDecipheriv(aes, key, iv);
decipher.setAuthTag(tag);
var decryptedData = decipher.update(text, 'hex', 'utf-8');
decryptedData += decipher.final('utf-8');
}

Resources