How to decipher the encrypted message using elliptic curve using JavaScript library? - javascript

I have found a library about Elliptic Curve Cryptography in JavaScript. I have learned how to encrypt the message. But, I didn't find how to decrypt it to the original message.
The code for encryption:
var EC = require('elliptic').ec;
var ec = new EC('secp256k1');
var msg = "hello";
let myKey = ec.keyFromPrivate('29f3c33a550d3810e6b82b7b510672118aeabcf8b19e00172e4623cbf480d2b8');
const sig = myKey.sign(msg, 'base64');
var derSign = sig.toDER('hex');
console.log (derSign)
output:
3044022076e7fbf80454f764e346dd359eb7f2002802e68d30a689d77d6211aa2c6e9d7302201b5f35d92b8f4aefd5f69d9d21e3dfba75404e4d5a89e09239b2accf43ff6d63
I want to return the signature to hello again. How I could do that, please?

I don't see any encrypt and decrypt function in elliptic, even in source code of library. In your demo code, it's a signature, not an encrypted message. You could use verify to validate the message whether is changed or not by some evil people..
console.log(myKey.verify(msg, derSign)); // true
console.log(myKey.verify(msg+"something_else", derSign)); // false
When the output is false, it's mean you message is changed, and true mean the message is not changed. That's how signature work, not encrypt or decrypt message.
So, if you want to encrypt and decrypt message with ecc, I guess you might use this library eccrypto.

Related

Different results trying to port SHA-1 digest from Python to browser JavaScript

Main question
I have the following short piece of legacy code that I am trying to port from Python (with just standard lib) to JavaScript - from the name of the methods I assume it creates a SHA-1 digest of the abc string
import hashlib
import hmac
print(hmac.new(b"abc", None, hashlib.sha1).hexdigest())
I searched for how to do that in the browser in JS and found the following code in the Mozilla documentation
var msgUint8 = new TextEncoder().encode('abc');
var hashBuffer = await crypto.subtle.digest('SHA-1', msgUint8);
var hashArray = Array.from(new Uint8Array(hashBuffer));
var hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
console.log(hashHex)
the problem is, they yield two completely different results, and I have no idea why:
cc47e3c0aa0c2984454476d061108c0b110177ae - Python
a9993e364706816aba3e25717850c26c9cd0d89d - JavaScript
I tried comparing the bytes of b"abc" with what new TextEncoder().encode('abc') returns and they are exactly the same: 0x61 0x62 0x63, so the problem lies somewhere else and I have no idea where.
I need the JavaScript code to return what the Python code returns. Any ideas?
Additionally
My final goal is to actually port this code (note the b"hello" instead of None):
print(hmac.new(b"abc", b"hello", hashlib.sha1).hexdigest())
so if you have an idea on that one too - I would hugely appreciate it!
The Python code calculates a SHA1 based HMAC. The JavaScript code on the other hand computes a SHA-1 hash. An HMAC needs a key in addition to the data, while a cryptographic hash function works without a key.
The first Python code uses the key abc and an empty message. The posted result for the HMAC is hex encoded:
cc47e3c0aa0c2984454476d061108c0b110177ae
The second Python code uses the same key and the message hello. The result for the HMAC is hex encoded:
d373670db3c99ebfa96060e993c340ccf6dd079e
The Java code determines the SHA-1 hash for abc. The result is
a9993e364706816aba3e25717850c26c9cd0d89d
So all results are correct, but are generated with different input data or algorithms.
The calculation of the HMAC can be implemented with the browser native WebCrypto-API as follows:
(async () => {
var hmac = await calcHMac('abc', 'hello');
console.log('HMAC: ', buf2hex(hmac));
var hmac = await calcHMac('abc', '');
console.log('HMAC: ', buf2hex(hmac));
})();
async function calcHMac(rawkey, data) {
var key = await window.crypto.subtle.importKey('raw', utf8Encode(rawkey), {name: 'HMAC', hash: 'SHA-1'},true, ['sign']);
var hmac = await window.crypto.subtle.sign('HMAC', key, utf8Encode(data));
return hmac;
}
function utf8Encode(str){
return new TextEncoder().encode(str);
}
function buf2hex(buffer) {
return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join(''); // from: https://stackoverflow.com/a/40031979/9014097
}
and provides the same result as the two Python codes.
A remark to SHA-1: Although HMAC/SHA-1 is considered to be secure (contrary to SHA-1), there are arguments to switch to SHA-256, see here.
The WebCrypto API is a bit cumbersome. A functionally identical implementation with CryptoJS, the library mentioned in the comment by Maurice Meyer, is simpler and looks like this:
var hmac = CryptoJS.HmacSHA1('hello', 'abc');
console.log('HMAC: ', hmac.toString(CryptoJS.enc.Hex));
var hmac = CryptoJS.HmacSHA1('', 'abc');
console.log('HMAC: ', hmac.toString(CryptoJS.enc.Hex));
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
but requires CryptoJS as external dependency.

TweetNaCl.js minimal Public-key signatures example

I am trying to understand how to implement a minimal basic Public-key signature example based on the demo located here, using pure javascript.
My research has not yielded a simple javascript example that I can use to understand its inner workings, and the documentation is over my head at the moment.
I tried looking at the source code of the demo, but it is not revealing its secrets.
The library's examples does not have an example for this either.
Cryptography is something very new to me, so any baseline example of how to create their Public-key example with pure javascript in node.js would be greatly appreciated!
Pseudocode-ish:
const nacl = require('tweetnacl')
let message = "This is my unencrypted message"
let naclPair = nacl.sign.keyPair()
let signedMessage = nacl.sign(message, naclPair.secretKey)
let decrypted = nacl.sign.open(signedMessage, naclPair.publicKey) // is this right?
console.log(decrypted) // should this print the decrypted message?
As a side note, I'm more familiar with node.js require, than I am with ES6 import, if that has any bearing on answers here and could help demonstrate how to use this library.
TweetNaCl.js is a port to JavaScript of TweetNaCl. TweetNacl in turn is a compact implementation of NaCl, which provides various encryption and signature algorithms essentially based on Curve25519. There are NaCl-compatible implementations or wrappers for many platforms, so that any of these documentations can be used for an introduction, e.g. the clear documentation of the Libsodium fork.
The documentation of TweetNaCl.js also gives a short overview of the functionality: nacl.sign(message, secretKey) creates a signed message consisting of the 64 bytes signature with attached message. nacl.sign.open(signedMessage, publicKey) verifies the message using the signature and returns the message if verification is successful. The algorithm used for signing is Ed25519.
As already noted in the comments, you do not distinguish clearly between encryption (purpose: secrecy) and signing (purpose: authentication / integrity). In particular, secrecy of the message is not the purpose of signing. This becomes apparent e.g. when the return of nacl.sign() contains the unencrypted message (see code snippet below). However, it is true that encryption with the private key is performed during signing (but not for the purpose of keeping it secret).
The following implementation is a pure JavaScript implementation:
var keyPair = nacl.sign.keyPair();
var secretKey = keyPair.secretKey;
var publicKey = keyPair.publicKey;
var msgStr = "The quick brown fox jumps over the lazy dog";
var msg = nacl.util.decodeUTF8(msgStr);
var signature = nacl.sign(msg, secretKey);
var signatureB64 = nacl.util.encodeBase64(signature);
console.log(signatureB64.replace(/(.{64})/g,'$1\n')); // Display signature plus message (Base64 encoded)
var signatureMsgPart = signature.slice(64);
console.log(nacl.util.encodeUTF8(signatureMsgPart)); // Display message from nacl.sign() return value: signing is not for encryption!
var verifiedMsg = nacl.sign.open(signature, publicKey);
console.log(nacl.util.encodeUTF8(verifiedMsg)); // Display message after successfull verification
<script src="https://cdn.jsdelivr.net/npm/tweetnacl-util#0.15.0/nacl-util.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/tweetnacl#1.0.1/nacl.min.js"></script>
and applies the package tweetnacl-util-js for encoding.
By the way, in the implementation you posted only the Utf8 encoding/decoding was missing:
let message = "This is my unencrypted message"
let naclPair = nacl.sign.keyPair()
let signedMessage = nacl.sign(nacl.util.decodeUTF8(message), naclPair.secretKey)
let decrypted = nacl.sign.open(signedMessage, naclPair.publicKey) // is this right? -> Yes
console.log(nacl.util.encodeUTF8(decrypted)) // should this print the decrypted message? -> Yes, but the 'verified' message is printed!
<script src="https://cdn.jsdelivr.net/npm/tweetnacl-util#0.15.0/nacl-util.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/tweetnacl#1.0.1/nacl.min.js"></script>
Please see the following links for public key encryption and symmetric encryption with TweetNaCl.js. This is about keeping a message secret.
By the way, using the example page(Public-key signatures) to test the code need to use nacl.sign.detached(message, secretKey) not nacl.sign(msg, secretKey) 😂
reference
TweetNaCl.js Public-key signatures example err

TripleDES encryption has different results in C# and JavaScript (CryptoJS)

I'm working on a project that uses an external API that is written in C#. In this API, I need to send some encrypted data while using their key that was provided when I started a session.
My project is built using NodeJS, so to do this encryption I am using the CryptoJS module. While talking with the API developer, he sent me a code showing how the encryption is made in C#. Here is the code with an example key and value to be encrypted.
TripleDESCryptoServiceProvider mDes = new TripleDESCryptoServiceProvider();
mDes.Key = Convert.FromBase64String("bv8czu/UPuZg6xNxnJAD/vRtbng9mQZX");
mDes.Mode = CipherMode.ECB;
mDes.Padding = PaddingMode.Zeros;
ICryptoTransform mDesEnc = mDes.CreateEncryptor();
byte[] data = Encoding.UTF8.GetBytes("1"); //value to encrypt
var crypto = Convert.ToBase64String(mDesEnc.TransformFinalBlock(data, 0, data.Length));
Console.WriteLine(crypto);
This results in the following encryption: 3EAaQjY2dgA=
As you can see in the code or running it, the encryption uses 3DES, mode ECB, Zero Padding and the key while in a byte array format has 24 bytes.
So I started to recreate this code in JavaScript and ended up with this:
var CryptoJS = require("crypto-js");
var encryptStringWith3DES = function(toEncrypt, key){
toEncrypt = "1";
key = "bv8czu/UPuZg6xNxnJAD/vRtbng9mQZX";
key = CryptoJS.enc.Utf8.parse(key);
console.log(toEncrypt + " " + key);
var encrypted = CryptoJS.TripleDES.encrypt(toEncrypt, key,{
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.ZeroPadding
}).toString();
console.log(encrypted);
}
And it results in the following encryption: dj1byXBV6ug=
I have searched for many answers and none worked. My suspicion is with how CryptoJS receives the key as a parameter and how the key and data are parsed.
Does any of you know how to make my JS code result in the same encrypted data as the C# one?

AES Encryption/Decryption in Node JS similar to Java

I am trying to replicate the Java code for AES Encryption and Decryption in Node JS.
Java Code
SecretKeySpec skeySpec;
String key = "a4e1112f45e84f785358bb86ba750f48";
public void encryptString(String key) throws Exception {
try {
skeySpec = new SecretKeySpec(key.getBytes(), "AES");
cipher = Cipher.getInstance("AES");
cipher.init(1, skeySpec);
byte encstr[] = cipher.doFinal(message.getBytes());
String encData = new String(encstr, "UTF-8");
System.out.println(encData);
} catch (NoSuchAlgorithmException nsae) {
throw new Exception("Invalid Java Version");
} catch (NoSuchPaddingException nse) {
throw new Exception("Invalid Key");
}
}
Node JS
var encryptKey = function (text) {
var cipher = crypto.createCipher('aes256', 'a4e1112f45e84f785358bb86ba750f48');
var crypted = cipher.update(text,'utf8', 'hex')
crypted += cipher.final('hex');
console.log(crypted);
return crypted;
}
I am unable to get the exact cipher-text in Node JS, which i am getting in Java.
Your code actually uses different encryption parameters in the 2 cases. AES, being a block cipher, takes: the plain text to encrypt, the initialization vector, also called IV (which is used in conjunction with the plaintext), and the encryption key.
In Java, the IV is, apparently, generated automatically on init() - from the Java SE platform docs for Cipher.init:
The generated parameters can be retrieved using getParameters or getIV
(if the parameter is an IV).
In Node.js, if using the deprecated createCipher function, the IV is generated automatically based on the provided key, probably in a different way than in Java, so you will get a different cipher text. However, you should be using the non-deprecated variant crypto.createCipheriv: https://nodejs.org/docs/latest-v12.x/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv_options
In order to exactly reproduce the cipher text, you should:
Use the same encryption algorithm on both sides - it's best to specify this exactly, for example aes-256-cbc, or an authenticated encryption scheme such as aes-256-gcm, which is harder to use but provides message authentication.
Use the same IV on both sides, by providing it in the initialization params in Java, and by using createCipheriv in Node; though beware, you should always randomize it in production! See https://stackoverflow.com/a/20888967/6098312
As a closing remark, when using block encryption, you'll usually be generating securely-random IVs, which means the ciphertexts will always differ from one another, even for the same plaintext. This is a good thing! It protects your payload from an attacker who observes the encrypted data and makes conclusions based on message repetitions.
Finally after reviewing Java Docs and Node JS Crypto Docs managed to get the result.
We have to use crypto.createCipheriv() instead of crypto.createCipher with a iv.
Here iv will be null.
Code :
let crypto = require('crypto');
var iv = new Buffer.from(''); //(null) iv
var algorithm = 'aes-256-ecb';
var password = 'a4e1112f45e84f785358bb86ba750f48'; //key password for cryptography
function encrypt(buffer){
var cipher = crypto.createCipheriv(algorithm,new Buffer(password),iv)
var crypted = Buffer.concat([cipher.update(buffer),cipher.final()]);
return crypted;
}
console.log(encrypt(new Buffer('TextToEncrypt')).toString())

Encrypting with EasyRSA in PHP and Decrypting with Node-RSA in JS

Problem
I'm trying to create a simple trustless file sharing application. I'm using EasyRSA (https://github.com/paragonie/EasyRSA) to create a key-pair and then encrypt my data with the public key. I'm sending the private key to my JS wherein I'm using Node-RSA (https://github.com/rzcoder/node-rsa). Here, I try to decrypt using the previously created private key. But this happens:
Error
Uncaught Error: Error during decryption (probably incorrect key). Original error: Error: Incorrect data or key
at NodeRSA.module.exports.NodeRSA.$$decryptKey (drop.js:23265)
at NodeRSA.module.exports.NodeRSA.decrypt (drop.js:23213)
at window.onload (drop.js:22270)
My JS code looks something like this:
var NodeRSA = require('node-rsa');
window.onload = function() {
var key_val = $('#key').val();
var ciphertext = $('#encrypted').val();
var key = new NodeRSA();
key.importKey($('#key').val(), 'pkcs1');
var ciphertext_base = key.encrypt(ciphertext, 'base64');
var decrypted_base = key.decrypt(btoa(ciphertext));
console.log(decrypted);
}
I think this has got something to do with the incompatibility between the formats/key-sizes/algos used to create the keys. If someone could help me 'hack' this and make it work, I would be very grateful to you.

Categories

Resources