web.crypto encryption c# decryption - javascript

I'm trying to do:
encrypt text using web.crypto,
decrypt text using AesCryptoServiceProvider
I didn't get any exceptions in my code, but the decryption doesn't match the plain text that i've encrypted
the plaintext bytes after decyption are the same, but the encoding to string doesn't work
I'm using random iv, the key and the plaintext are constant.
function cryptoSys(plaintext,KeyString){
var iVec=window.crypto.getRandomValues(new Uint8Array(16));
var encryptSuccessFunc=(encrypt)=> { AfterEncrypt(BytearrayToString(iVec),arraybufferTostring(encrypt));}
var ImportKeySuccessFunc= (keyObj)=>{
window.crypto.subtle.encrypt(
{name:"AES-CBC", iv:iVec},
keyObj,
StringToByteArray(plaintext)
).then(encryptSuccessFunc);
window.crypto.subtle.importKey(
"raw",
StringToByteArray(KeyString),
{name:"AES-CBC", length:128},
true,
["encrypt","decrypt"]
).then(ImportKeySuccessFunc);
}
After that I'm sending the iVec, ciphertext using json
function AfterEncrypt(iVec,ciphertext)
{
var plaintext="String to Encrypt";
if(iVec==null)
return;
var send2server= {"ciphertext":ciphertext,
"iVec":iVec,
"plaintext":plaintext};
var objectDataString = JSON.stringify(send2server);
sendJSONtoserver(objectDataString,"getDelayedBid");
}
I'm using the following utility functions :
function StringToByteArray(strString) {
var byteArray = new Uint8Array(strString.length);
for (var i=0; i<strString.length; i++) {
byteArray[i] = strString.charCodeAt(i);
}
return byteArray;
}
function BytearrayToString(arrayBuffer) {
var strString = "";
for (var i=0; i<arrayBuffer.byteLength; i++) {
strString += String.fromCharCode(arrayBuffer[i]);
}
return strString;
}
function arraybufferTostring(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
server side accepts the keys, and suppose to decrypt:
public string DecryptCipher(Encoding u16, string cipherText, string key,string iVec)
{
byte[] ciphertextBytes = clearZeros(u16.GetBytes(cipherText));
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.BlockSize = 128;
aes.KeySize = 128; //minimun key length
aes.Key = clearZeros(u16.GetBytes(key));
aes.IV = clearZeros(u16.GetBytes(iVec));
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
ICryptoTransform cryptoTrans = aes.CreateDecryptor(aes.Key, aes.IV);
byte[] plaintextBytes = cryptoTrans.TransformFinalBlock(ciphertextBytes, 0, ciphertextBytes.Length);
cryptoTrans.Dispose();
return Convert.ToBase64String(plaintextBytes);
}
I've got this utility function as well:
private byte [] clearZeros(byte [] bytearray)
{
byte[] ans = new byte[bytearray.Length / 2];
for (int i = 0; i < bytearray.Length / 2; i++)
ans[i] = bytearray[2 * i];
return ans;
}
I'm getting the paramters from anthor function:
public ActionResult getDelayedBid([FromBody] DelayedSubmission delaySub)
{
if (delaySub.ciphertext == null)
return Json("Failure", JsonRequestBehavior.AllowGet);
Encoding u16LE = Encoding.Unicode;
String decrypetedMessageLE = new Encryption().DecryptCipher(u16LE, delaySub.ciphertext, getKeyFromDB(), delaySub.iVec);
if (decrypetedMessageLE.Equals(delaySub.plaintext) )
{
return Json("Success", JsonRequestBehavior.AllowGet);
}
return Json("Failure", JsonRequestBehavior.AllowGet);
}

I've used wrong Ecoding,
instand of
Convert.ToBase64String(plaintextBytes);
I should've used
Encoding.ASCII.GetString(plaintextBytes);

Related

Why does signing algorithm in C# give different result than the one in Javascript

This is the algorithm for signing the data in C# using a private key from a certificate that is used from both me and the client in order to define an unique key to identify the user:
X509Certificate2 keyStore = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + "Certifikatat\\" + certPath, certPass, X509KeyStorageFlags.Exportable);
RSA privateKey = keyStore.GetRSAPrivateKey();
byte[] iicSignature = privateKey.SignData(Encoding.ASCII.GetBytes("K31418036C|2022-5-16 13:30:41|406|st271ir481|al492py609|zz463gy579|340"), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
byte[] iic = ((HashAlgorithm)CryptoConfig,CreateFromName("MD5")).ComputeHash(iicSignature);
I then pass the private key to my Javascript using Bouncy Castle:
X509Certificate2 keyStore = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + "Certifikatat\\" + certPath, certPass, X509KeyStorageFlags.Exportable);
RSA privateKey = keyStore.GetRSAPrivateKey();
var eky = DotNetUtilities.GetRsaKeyPair(privateKey);
Pkcs8Generator pkcs8Gen = new Pkcs8Generator(eky.Private);
Org.BouncyCastle.Utilities.IO.Pem.PemObject pkcs8 = pkcs8Gen.Generate();
PemWriter pemWriter = new PemWriter(new StringWriter());
pemWriter.WriteObject(pkcs8);
pemWriter.Writer.Flush();
return pemWriter.Writer.ToString();
This one is the algorithm used in Javascript:
window.crypto.subtle.importKey(
"pkcs8",
pemToArrayBuffer(pkcs8Pem), {
name: "RSASSA-PKCS1-v1_5",
hash: {
name: "SHA-256"
},
},
false, ["sign"]
)
.then(function(privateKey) {
console.log(privateKey);
// Sign: RSA with SHA256 and PKCS#1 v1.5 padding
window.crypto.subtle.sign({
name: "RSASSA-PKCS1-v1_5",
},
privateKey,
new TextEncoder().encode("K31418036C|2022-5-16 13:30:41|406|st271ir481|al492py609|zz463gy579|340")
)
.then(function(signature) {
var iic = md5(signature);
console.log(ab2b64(signature));
})
.catch(function(err) {
console.error(err);
});
})
.catch(function(err) {
console.error(err);
});
function ab2b64(arrayBuffer) {
return window.btoa(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer)));
}
function removeLines(str) {
str = str.replace("\r", "");
return str.replace("\n", "");
}
function base64ToArrayBuffer(b64) {
var byteString = atob(b64);
var byteArray = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
byteArray[i] = byteString.charCodeAt(i);
}
return byteArray;
}
function pemToArrayBuffer(pem) {
var b64Lines = removeLines(pem);
var b64Prefix = b64Lines.replace('-----BEGIN PRIVATE KEY-----', '');
var b64Final = b64Prefix.replace('-----END PRIVATE KEY-----', '');
return base64ToArrayBuffer(b64Final);
}
The signatures returned are different for some reason. I need them to be the same or else it's all pointless because the client won't be authenticated.
The results are as follow:
C#:
57CF663ACBEDE6305309682BA7261412
Javascript:
c099d176dcd95c59d748d6066dcd462e
I had to convert my signature to base64 and then encode it with atob() after that i needed this md5 library to hash the data and then use .toUpperCase() to reproduce the correct result.
The complete code looks like this:
md5(atob(ab2b64(signature))).toUpperCase();
Now i get the same result from both C# and JS.

This is a Python code to get a md5 digest of a signature, Need help to implement this thing in JavaScript

Python Code that works fine and I checked this Python code for message "a" it gives me the result "52F17E7031982DE1744A57F6EE9BD3A3"
from Crypto.Hash import SHA256, MD5
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from OpenSSL import crypto
message = "a".encode('utf-8')
p12 = crypto.load_pkcs12(company_p12_certificate, certificate_password)
key_bytes = crypto.dump_privatekey(crypto.FILETYPE_PEM, p12.get_privatekey())
key = RSA.import_key(key_bytes)
h = SHA256.new(message)
signer = PKCS1_v1_5.new(key)
signature = signer.sign(h)
md5_digest = MD5.new(signature)
result = str(md5_digest.digest().hex()).upper()
I implemented this using JavaScript but not getting same result. It gives me "4EB5DB7F5459E832DE3E0638A8F4C4A0" for message "a"
My JavaScript code is:
$(document).ready(function () {
function _privateKeyToPkcs8(privateKey) {
var rsaPrivateKey = forge.pki.privateKeyToAsn1(privateKey);
var privateKeyInfo = forge.pki.wrapRsaPrivateKey(rsaPrivateKey);
var privateKeyInfoDer = forge.asn1.toDer(privateKeyInfo).getBytes();
var privateKeyInfoDerBuff = stringToArrayBuffer(privateKeyInfoDer);
return privateKeyInfoDerBuff;
}
function stringToArrayBuffer(data) {
var arrBuff = new ArrayBuffer(data.length);
var writer = new Uint8Array(arrBuff);
for (var i = 0, len = data.length; i < len; i++) {
writer[i] = data.charCodeAt(i);
}
return arrBuff;
}
function arrayBufferToString(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 binary;
}
$("#file").change(function () {
var file = this.files[0];
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function (e) {
var contents = e.target.result;
var pkcs12Der = arrayBufferToString(contents)
var pkcs12B64 = forge.util.encode64(pkcs12Der);
var pkcs12Der = forge.util.decode64(pkcs12B64);
var pkcs12Asn1 = forge.asn1.fromDer(pkcs12Der);
var pkcs12 = forge.pkcs12.pkcs12FromAsn1(pkcs12Asn1, false, '123456');
var privateKey
for (var sci = 0; sci < pkcs12.safeContents.length; ++sci) {
var safeContents = pkcs12.safeContents[sci];
for (var sbi = 0; sbi < safeContents.safeBags.length; ++sbi) {
var safeBag = safeContents.safeBags[sbi];
// this bag has a private key
if (safeBag.type === forge.pki.oids.keyBag) {
//Found plain private key
privateKey = safeBag.key;
} else if (safeBag.type === forge.pki.oids.pkcs8ShroudedKeyBag) {
// found encrypted private key
privateKey = safeBag.key;
} else if (safeBag.type === forge.pki.oids.certBag) {
// this bag has a certificate...
}
}
}
var privateKeyInfoDerBuff = _privateKeyToPkcs8(privateKey);
//Import the webcrypto key
crypto.subtle.importKey(
'pkcs8',
privateKeyInfoDerBuff,
{ name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } },
true,
["sign"]).
then(function (cryptoKey) {
var sha256 = forge.md.sha256.create();
sha256.update('a'); // Message will come here
var digestToSignBuf = stringToArrayBuffer(sha256.digest().toHex());
crypto.subtle.sign({ name: "RSASSA-PKCS1-v1_5" }, cryptoKey, digestToSignBuf)
.then(function (signature) {
var signatureB64 = forge.util.encode64(arrayBufferToString(signature))
var md5 = forge.md.md5.create();
md5.update(signatureB64);
console.log("final result", md5.digest().toHex().toUpperCase());
});
})
}
})
});
I also checked https://github.com/digitalbazaar/forge
WebCrypto implicitly generates the hash of the data during signing using the digest SHA-256 specified in the key, so explicit hashing with SHA-256 is not necessary.
Also, the generated signature is directly hashed with MD5, i.e. without prior Base64 encoding.
With these changes, the JavaScript code is (using a test key):
// Import private test key
var pkcs8pem = `-----BEGIN PRIVATE KEY-----
MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEA2gdsVIRmg5IH0rG3
u3w+gHCZq5o4OMQIeomC1NTeHgxbkrfznv7TgWVzrHpr3HHK8IpLlG04/aBo6U5W
2umHQQIDAQABAkEAu7wulGvZFat1Xv+19BMcgl3yhCdsB70Mi+7CH98XTwjACk4T
+IYv4N53j16gce7U5fJxmGkdq83+xAyeyw8U0QIhAPIMhbtXlRS7XpkB66l5DvN1
XrKRWeB3RtvcUSf30RyFAiEA5ph7eWXbXWpIhdWMoe50yffF7pW+C5z07tzAIH6D
Ko0CIQCyveSTr917bdIxk2V/xNHxnx7LJuMEC5DcExorNanKMQIgUxHRQU1hNgjI
sXXZoKgfaHaa1jUZbmOPlNDvYYVRyS0CIB9ZZee2zubyRla4qN8PQxCJb7DiICmH
7nWP7CIvcQwB
-----END PRIVATE KEY-----`;
var pkcs8 = convertDER(pkcs8pem);
crypto.subtle.importKey(
'pkcs8',
pkcs8,
{ name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } },
true,
["sign"])
.then(function (cryptoKey) {
// Sign message
var message = 'The quick brown fox jumps over the lazy dog';
crypto.subtle.sign(
{ name: "RSASSA-PKCS1-v1_5" },
cryptoKey,
stringToArrayBuffer(message))
.then(function (signature) {
// Create MD5 hash
var md5 = forge.md.md5.create();
md5.update(arrayBufferToString(signature));
console.log("Final result", md5.digest().toHex().toUpperCase()); // Final result 30FD001CFD12D0A3DF000D216C82C47E
});
});
// Helper
function stringToArrayBuffer(data) {
var arrBuff = new ArrayBuffer(data.length);
var writer = new Uint8Array(arrBuff);
for (var i = 0, len = data.length; i < len; i++) {
writer[i] = data.charCodeAt(i);
}
return arrBuff;
}
function arrayBufferToString(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 binary;
}
function convertDER(pem){
var pemHeader = "-----BEGIN PRIVATE KEY-----";
var pemFooter = "-----END PRIVATE KEY-----";
var pemContents = pkcs8pem.substring(pemHeader.length, pkcs8pem.length - pemFooter.length);
var binaryDerString = window.atob(pemContents);
var pkcs8 = stringToArrayBuffer(binaryDerString);
return pkcs8;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/forge/0.10.0/forge.min.js"></script>
with the output:
Final result 30FD001CFD12D0A3DF000D216C82C47E
The Python code returns the same result for the same key and plaintext.
from Crypto.Hash import SHA256, MD5
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
key_bytes = '''-----BEGIN PRIVATE KEY-----
MIIBVQI...
-----END PRIVATE KEY-----'''
message = "The quick brown fox jumps over the lazy dog".encode('utf-8')
key = RSA.import_key(key_bytes)
h = SHA256.new(message)
signer = PKCS1_v1_5.new(key)
signature = signer.sign(h)
md5_digest = MD5.new(signature)
result = str(md5_digest.digest().hex()).upper()
print(result) # 30FD001CFD12D0A3DF000D216C82C47E
As already noted in the comments, due to the MD5 hash, verification using the public key is not possible (but apparently not intended).
Also, WebCrypto provides the SubtleCrypto.digest() function to determine a hash, so the forge library is actually not really necessary (at least for hashing).
I've not analyzed the key import in more detail, so there may be problems here as well.

RSA-OAEP encryption in Javascript and decryption in Java

I am currently implementing the RSA-OAEP encryption on Javascript and decryption at Java.
My javascript code has the following
function stringToArrayBuffer(str){
var buf = new ArrayBuffer(str.length);
var bufView = new Uint8Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
function arrayBufferToString(str){
var byteArray = new Uint8Array(str);
var byteString = '';
for(var i=0; i < byteArray.byteLength; i++) {
byteString += String.fromCodePoint(byteArray[i]);
}
return byteString;
}
function encryptDataWithPublicKey(data, key) {
data = stringToArrayBuffer(data);
return window.crypto.subtle.encrypt(
{
name: "RSA-OAEP",
//label: Uint8Array([...]) //optional
},
key, //from generateKey or importKey above
data //ArrayBuffer of data you want to encrypt
);
}
var pem = Config.encryption.publicKey;
// fetch the part of the PEM string between header and footer
const pemHeader = "-----BEGIN PUBLIC KEY-----";
const pemFooter = "-----END PUBLIC KEY-----";
const pemContents = pem.substring(pemHeader.length, pem.length - pemFooter.length);
// base64 decode the string to get the binary data
const binaryDerString = window.atob(pemContents);
// convert from a binary string to an ArrayBuffer
const binaryDer = stringToArrayBuffer(binaryDerString);
window.crypto.subtle.importKey(
"spki",
binaryDer,
{
name: "RSA-OAEP",
hash: { name: "SHA-256" }
},
true,
["encrypt"]
).then(function (publicKey) {
encryptDataWithPublicKey(text, publicKey).then((result) => {
var rdata = arrayBufferToString(result);
resolve(rdata);
});
}).catch(function (err) {
console.log(err);
reject(err);
});
I also have a Java function to decrypt the text. Assume "rsaOaepCipherText" is a string text.
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");
OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), PSource.PSpecified.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(), oaepParams);
return new String(cipher.doFinal(Base64.decodeBase64(rsaOaepCipherText)), "UTF-8");
However I keep getting decryption error on Java, and currently stuck at this portion, is there any error I have done on my encryption on Javascript?
Ok found it. I forgot to include btoa on the string before send to backend.
it should be
encryptDataWithPublicKey(text, publicKey).then((result) => {
var rdata = arrayBufferToString(result);
var rResult = window.btoa(rdata);
resolve(rResult);
});

AES256 NodeJS Decrypt

My clean data is : Test12345678910
My secret key is : 12345678901234561234567890123456
When i encrypt the data i get this output : ldJbAK2rYjDnS6kWz2O+Aw==
when i decrypt it i get error
internal/crypto/cipher.js:164
const ret = this._handle.final();
^
Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
my code is ;
const crypto = require('crypto');
const encrypted = "ldJbAK2rYjDnS6kWz2O+Aw==";
const key = "12345678901234561234567890123456";
let decipher = crypto.createDecipher('aes-256-cbc', key);
let decrypted = decipher.update(encrypted);
decrypted = [decrypted, decipher.final("utf-8")];
console.log(decrypted.toString());
Encrypting from C#
public static string EncryptToken(string text)
{
string confkey = "12345678901234561234567890123456";
byte[] array;
try
{
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(confkey);
aes.IV = new byte[16];
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
{
streamWriter.Write(text);
}
array = memoryStream.ToArray();
}
}
}
return Convert.ToBase64String(array);
}
catch
{
return string.Empty;
}
}

how to decrypt in nodejs which is encrypted using JAVA

im trying to convert java lambda into javascript lamda. want to convert these encrypt and decrypt method which is written in java to node js or javascript.
I have tried to implement using crpto in node
keys are like this
private static String CIPHER_NAME = "AES/CBC/PKCS5PADDING";
private static int CIPHER_KEY_LEN = 16; //128 bits
encrypt method
private String encrypt(String key, String iv, String data) {
try {
if (key.length() <CIPHER_KEY_LEN) {
int numPad = CIPHER_KEY_LEN - key.length();
for(int i = 0; i < numPad; i++){
key += "0"; //0 pad to len 16 bytes
}
} else if (key.length() >CIPHER_KEY_LEN) {
key = key.substring(0, CIPHER_KEY_LEN); //truncate to 16 bytes
}
IvParameterSpec initVector = new IvParameterSpec(iv.getBytes("ISO-8859-1"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("ISO-8859-1"), "AES");
Cipher cipher = Cipher.getInstance(CIPHER_NAME);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, initVector);
byte[] encryptedData = cipher.doFinal((data.getBytes()));
String base64_EncryptedData = Base64.getEncoder().encodeToString(encryptedData);
String base64_IV = Base64.getEncoder().encodeToString(iv.getBytes("ISO-8859-1"));
return base64_EncryptedData + ":" + base64_IV;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
decrypt method
private String decrypt(String key, String data) {
try {
if (key.length() < CIPHER_KEY_LEN) {
int numPad = CIPHER_KEY_LEN - key.length();
for(int i = 0; i < numPad; i++){
key += "0"; //0 pad to len 16 bytes
}
} else if (key.length() > CIPHER_KEY_LEN) {
key = key.substring(0, CIPHER_KEY_LEN); //truncate to 16 bytes
}
String[] parts = data.split(":");
IvParameterSpec iv = new IvParameterSpec(Base64.getDecoder().decode(parts[1]));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("ISO-8859-1"), "AES");
Cipher cipher = Cipher.getInstance(CIPHER_NAME);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] decodedEncryptedData = Base64.getDecoder().decode(parts[0]);
byte[] original = cipher.doFinal(decodedEncryptedData);
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
I have used
this is the solution i made but seems it not working cause i encrypted this using a java code and using node's javascript code to decrypt it.
function decrypt (messagebase64, keyBase64, ivBase64) {
var key = Buffer.from(keyBase64, 'base64');
var iv = Buffer.from(ivBase64, 'base64');
var decipher = crypto.createDecipheriv(getAlgorithm(keyBase64), key, iv);
decipher.setAutoPadding(false);
decipher.update(messagebase64, 'base64');
return decipher.final();
}
find the alogorithm i use this and adding padding if the key is not long enough but this give error that saying length is not enough.
function getAlgorithm(keyBase64) {
if(keyBase64.length<CIPHER_KEY_LEN){
var padding = CIPHER_KEY_LEN-keyBase64.length;
for(var i=0;i<padding;i++){
keyBase64+="0";
}
}else if(keyBase64.length>CIPHER_KEY_LEN){
keyBase64 =keyBase64.substring(0, CIPHER_KEY_LEN)
}
var key = Buffer.from(keyBase64, 'base64');
switch (key.length) {
case 16:
return 'aes-128-cbc';
case 32:
return 'aes-256-cbc';
}
throw new Error('Invalid key length: ' + key.length);
}
after struggling for a while i have implemented encrypted method and decrypt method which will be identical to java.
decrypt method
function decrypt (messagebase64, keyBase64, ivBase64) {
if(keyBase64.length<CIPHER_KEY_LEN){
var padding = CIPHER_KEY_LEN-keyBase64.length;
for(var i=0;i<padding;i++){
keyBase64+="0";
}
}else if(keyBase64.length>CIPHER_KEY_LEN){
keyBase64 =keyBase64.substring(0, CIPHER_KEY_LEN)
}
var key = Buffer.from(keyBase64, 'latin1');
var iv = Buffer.from(ivBase64, 'base64');
var encryptdata = new Buffer(messagebase64, 'base64');
var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv),
decoded = decipher.update(encryptdata, 'base64', 'utf8');
decoded += decipher.final('utf8');
return decoded
}
encrypt method
function encrypt(plainText, keyBase64, ivBase64) {
if(keyBase64.length<CIPHER_KEY_LEN){
var padding = CIPHER_KEY_LEN-keyBase64.length;
for(var i=0;i<padding;i++){
keyBase64+="0";
}
}else if(keyBase64.length>CIPHER_KEY_LEN){
keyBase64 =keyBase64.substring(0, CIPHER_KEY_LEN)
}
var key = Buffer.from(keyBase64, 'latin1');
var iv = Buffer.from(ivBase64,'latin1');
var encoded_base64_iv= iv.toString('base64');
var cipher2 = crypto.createCipheriv('aes-128-cbc', key, iv);
cipher2.write(plainText);
cipher2.end();
var cipher_text = cipher2.read();
var encodedString = cipher_text.toString('base64');
var final_encrypted_data = encodedString+":"+encoded_base64_iv;
return final_encrypted_data.toString();
};

Categories