Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@joshi-kumar
Created February 17, 2018 11:49
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save joshi-kumar/52bd2b6a79a2dab04c0fe5534f4a5757 to your computer and use it in GitHub Desktop.
Save joshi-kumar/52bd2b6a79a2dab04c0fe5534f4a5757 to your computer and use it in GitHub Desktop.
Encrypt code in js and decrypt the code in c# (.cs)
c# code
public string DecryptStringAES(string encryptedValue)
{
var keybytes = Encoding.UTF8.GetBytes("7061737323313233");
var iv = Encoding.UTF8.GetBytes("7061737323313233");
//DECRYPT FROM CRIPTOJS
var encrypted = Convert.FromBase64String(encryptedValue);
var decriptedFromJavascript = DecryptStringFromBytes(encrypted, keybytes, iv);
return decriptedFromJavascript;
}
private static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
{
throw new ArgumentNullException("cipherText");
}
if (key == null || key.Length <= 0)
{
throw new ArgumentNullException("key");
}
if (iv == null || iv.Length <= 0)
{
throw new ArgumentNullException("key");
}
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (var rijAlg = new RijndaelManaged())
{
//Settings
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.PKCS7;
rijAlg.FeedbackSize = 128;
rijAlg.Key = key;
rijAlg.IV = iv;
// Create a decrytor to perform the stream transform.
var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (var msDecrypt = new MemoryStream(cipherText))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
*****************************************************************************************
js code
--------
function Encryption(number) {
console.log(number);
var key = CryptoJS.enc.Utf8.parse('7061737323313233');
var iv = CryptoJS.enc.Utf8.parse('7061737323313233');
var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(number), key,
{
keySize: 128 / 8,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString();
}
@gyswamy
Copy link

gyswamy commented Aug 22, 2018

How can we use dynamic values for key and iv instead of static? Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment