C# equivalent of LZMA-JS compress - javascript

I have used some client side javscript code to compress some user input using this javascript library.
In the backend code I have used the code samples from this post to decompress the data server side using C#.
The works perfectly.
Now I would like to be able to compress a string the same way the javascript does. When I compress the code using this sample I get an array of signed integers ranging from -128 to 128. Now I would like to use my backend code to do the same.
The LMZA properties from the javascript are a bit different than the default properties from the C# code but even if I change those to the same values I get different results from the two libraries.
At first the output values from the C# code are unsigned.
Secondly the number of characters returned are different.
The differences may be introduced by the properties of the decoders but I have no idea how to get the two libraries aligned.
My C# uses the LMZA SDK from 7zip
My C# code to decompress the javascript compressed data (comma separated array of signed integers):
public static void Decompress(Stream inStream, Stream outStream)
{
byte[] properties = new byte[5];
inStream.Read(properties, 0, 5);
SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder();
decoder.SetDecoderProperties(properties);
long outSize = 0;
for (int i = 0; i < 8; i++)
{
int v = inStream.ReadByte();
outSize |= ((long)(byte)v) << (8 * i);
}
long compressedSize = inStream.Length - inStream.Position;
decoder.Code(inStream, outStream, compressedSize, outSize, null);
}
public static string DecompressLzma(string inputstring)
{
if (!string.IsNullOrEmpty(inputstring))
{
byte[] myInts = Array.ConvertAll(inputstring.Split(','), s => (byte)int.Parse(s));
var stream = new MemoryStream(myInts);
var outputStream = new MemoryStream();
Decompress(stream, outputStream);
using (var reader = new StreamReader(outputStream))
{
outputStream.Position = 0;
string output = reader.ReadToEnd();
return output;
}
}
return "";
}
The code to compress the data is like this (number of bytes are diffrent and unsigned):
public static string CompressLzma(string inputstring)
{
if (!string.IsNullOrEmpty(inputstring))
{
var stream = new MemoryStream(Encoding.Unicode.GetBytes(inputstring ?? ""));
var outputStream = new MemoryStream();
Compress(stream, outputStream);
byte[] bytes = outputStream.ToArray();
}
return "";
}
public static void Compress(MemoryStream inStream, MemoryStream outStream)
{
CoderPropID[] propIDs;
object[] properties;
PrepareEncoder(out propIDs, out properties);
SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder();
encoder.SetCoderProperties(propIDs, properties);
encoder.WriteCoderProperties(outStream);
Int64 fileSize = inStream.Length;
for (int i = 0; i < 8; i++)
{
outStream.WriteByte((Byte)(fileSize >> (8 * i)));
}
encoder.Code(inStream, outStream, -1, -1, null);
}
public static void PrepareEncoder(out CoderPropID[] propIDs, out object[] properties)
{
bool eos = true;
Int32 dictionary = 1 << 16;
Int32 posStateBits = 2;
Int32 litContextBits = 3; // for normal files
// UInt32 litContextBits = 0; // for 32-bit data
Int32 litPosBits = 0;
// UInt32 litPosBits = 2; // for 32-bit data
Int32 algorithm = 2;
Int32 numFastBytes = 32;
string mf = "bt2";
propIDs = new CoderPropID[]
{
CoderPropID.DictionarySize,
CoderPropID.PosStateBits,
CoderPropID.LitContextBits,
CoderPropID.LitPosBits,
CoderPropID.Algorithm,
CoderPropID.NumFastBytes,
CoderPropID.MatchFinder,
CoderPropID.EndMarker
};
properties = new object[]
{
dictionary,
posStateBits,
litContextBits,
litPosBits,
algorithm,
numFastBytes,
mf,
eos
};
}

This code works to create the same string the javascript code would, the LMZA settings are included:
public static string CompressLzma(string inputstring)
{
if (!string.IsNullOrEmpty(inputstring))
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(inputstring ?? ""));
var outputStream = new MemoryStream();
Compress(stream, outputStream);
byte[] bytes = outputStream.ToArray();
var result = string.Join(",", Array.ConvertAll(bytes, v => signedInt((int)v)));
return result;
}
return "";
}
public static void PrepareEncoder(out CoderPropID[] propIDs, out object[] properties)
{
bool eos = true;
Int32 dictionary = 1 << 16;
Int32 posStateBits = 2;
Int32 litContextBits = 3; // for normal files
// UInt32 litContextBits = 0; // for 32-bit data
Int32 litPosBits = 0;
// UInt32 litPosBits = 2; // for 32-bit data
Int32 algorithm = 2;
Int32 numFastBytes = 64;
string mf = "bt4";
propIDs = new CoderPropID[]
{
CoderPropID.DictionarySize,
CoderPropID.PosStateBits,
CoderPropID.LitContextBits,
CoderPropID.LitPosBits,
CoderPropID.Algorithm,
CoderPropID.NumFastBytes,
CoderPropID.MatchFinder,
CoderPropID.EndMarker
};
properties = new object[]
{
dictionary,
posStateBits,
litContextBits,
litPosBits,
algorithm,
numFastBytes,
mf,
eos
};
}
private static int signedInt(int unsignedInt)
{
return unsignedInt >= 128 ? Math.Abs(128 - unsignedInt) - 128 : unsignedInt;
}
public static void Compress(MemoryStream inStream, MemoryStream outStream)
{
CoderPropID[] propIDs;
object[] properties;
PrepareEncoder(out propIDs, out properties);
SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder();
encoder.SetCoderProperties(propIDs, properties);
encoder.WriteCoderProperties(outStream);
Int64 fileSize = inStream.Length;
for (int i = 0; i < 8; i++)
{
outStream.WriteByte((Byte)(fileSize >> (8 * i)));
}
encoder.Code(inStream, outStream, -1, -1, null);
}

Related

Replication of HMACSHA256 in c# as that of jsSHA

so i am trying to get this hash 69F6617707D9442940C39BEBFA0B4459CEBF6CD5E610EA1FF44B341E291654A9 which can me made on https://caligatio.github.io/jsSHA/.
The key is K = E74A540FA07C4DB1B46421126DF7AD36 , Message is T= 537707AD486F07AD75CCF7B1F7FEA6F75871FCF6DC755923C8EE7C375C21EAC51BD97C51C69F395B and the generated hash via my code is SHA256 (T) = 6a2783d8eb0237e015f7dcd27fb2d2a85dd637220433dffcdc31198670f6ecac
This is incorrect Hash.
This is my code can someone explain what is wrong here thanks.
static void Main(string[] args)
{
var key = "E74A540FA07C4DB1B46421126DF7AD36";
string message = "537707AD486F07AD75CCF7B1F7FEA6F75871FCF6DC755923C8EE7C375C21EAC51BD97C51C69F395B";
var encodingCred = new System.Text.ASCIIEncoding();
var encodingKey = new System.Text.ASCIIEncoding();
byte[] keyByte = StringToByteArray(key);
byte[] credentialsBytes = encodingCred.GetBytes(message);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(credentialsBytes);
string hash = BitConverter.ToString(hashmessage).Replace("-", string.Empty).ToLower();
Console.WriteLine("HASH: " + hash);
}
Console.ReadKey();
}
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
In C this is valid
void test_keyed_hmac()
{
hmac_sha256 hmac;
sha256 sha;
uint8_t sha_digest[32] = { 0 };
unsigned char key[] = "\xE7\x4A\x54\x0F\xA0\x7C\x4D\xB1\xB4\x64\x21\x12\x6D\xF7\xAD\x36";
//unsigned char key[] = "E74A540FA07C4DB1B46421126DF7AD36";
unsigned char data[] = "\x53\x77\x07\xAD\x48\x6F\x07\xAD\x75\xCC\xF7\xB1\xF7\xFE\xA6\xF7\x58\x71\xFC\xF6\xDC\x75\x59\x23\xC8\xEE\x7C\x37\x5C\x21\xEA\xC5\x1B\xD9\x7C\x51\xC6\x9F\x39\x5B";
//unsigned char data[] = "537707AD486F07AD75CCF7B1F7FEA6F75871FCF6DC755923C8EE7C375C21EAC51BD97C51C69F395B";
printf("Data length %d \n", strlen(data));
hmac_sha256_initialize(&hmac, key, strlen(key));
// Finalize the HMAC-SHA256 digest and output its value.
hmac_sha256_finalize(&hmac, data, strlen(data));
for (int i = 0; i < 32; ++i) {
// Cast added by RKW to get format specifier to work as expected
printf("%x", (unsigned long)hmac.digest[i]);
}
putchar('\n');
}
I need something like this in c# that gives the valid hash mentioned above in second line

Java and JavaScript hash with SHA-256 difference result

I do hash from Java and Compare with Java Script Code using same SHA-256 but the result seem different. Did anyone know help me on these please. Here is the code below.
Java Code
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
private static String salt = "Apple#987";
private static byte[] saltArr = salt.getBytes();
public static String getSHA256(String data) {
StringBuilder sb = new StringBuilder();
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(saltArr);
byte[] byteData = md.digest(data.getBytes());
sb.append(bytesToHex(byteData));
} catch(Exception e) {
e.printStackTrace();
}
return sb.toString();
}
private static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return String.valueOf(hexChars);
}
String hashed = getSHA256("SampleData");
System.out.println("hashed");
Java Script Code (In Postman)
var salt = 'Apple#987';
var data = 'SampleData';
var hash = CryptoJS.HmacSHA256(data, salt).toString(CryptoJS.enc.Hex);
Java Result:
7B2BBE6DAD962170A83A911EE7B84A382DE2F7FA0DA77C55F99F696EEFAF6C5D
Java Script Result:
1de0de12c5f22bf98f2dbae8430470cac64875a28a035191c3f783e6a2d6cb3b
the Javascript result(1de0de12c5f22bf98f2dbae8430470cac64875a28a035191c3f783e6a2d6cb3b) is right,check it in this link
Java Code you can refer this link
String key = "Apple#987";
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
sha256_HMAC.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));
byte[] result = sha256_HMAC.doFinal("SampleData".getBytes());
System.out.println (DatatypeConverter.printHexBinary(result));
javascript code:
var result = crypto.createHmac('SHA256', 'Apple#987').update('SampleData').digest('hex')
console.log(result)
thanks.

AES-256(CBC) : encryption in Java/Decryption in JavaScript(CryptoJS)

I am doing encryption in Java and decrypting it with JavaScript using AES-256/CBC, but actually this is the scenario:
while encryption of .pdf, .jpg, in other words, other than text files Java produces the encrypted file with roughly the same bytes but in case of JavaScript(CryptoJS) it outputs ~1.5 times of the original file size, which is why I think for the decryption with CryptoJS it does not expect the small encrypted file size from Java. I have given the code from both sides i.e, encryption at Java side, decryption at JavaScript side.
Problem:
I have a requirement of encrypting any file with Java and decrypting the same file with JavaScript. Kindly refer to the code as given below and this example.
Java: Encryption
key generation:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), hex(salt), iterationCount, keySize);
SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
Encryption:
params:
private static final String IV = "F27D5C9927726BCEFE7510B1BDD3D137";
private static final String SALT = "3FF2EC019C627B945225DEBAD71A01B6985FE84C95A70EB132882F88C0A59A55";
private static final int KEY_SIZE = 128;
private static final int ITERATION_COUNT = 10000;
private static final String PASSWORD = "SET_YOUR_PASSWORD_HERE";
code:
public String encrypt(String salt, String iv, String passphrase, String plaintext) {
try {
SecretKey key = generateKey(salt, passphrase);
byte[] encrypted = doFinal(Cipher.ENCRYPT_MODE, key, iv, plaintext.getBytes("UTF-8"));
return base64(encrypted);
} catch (Exception e) {
throw fail(e);
}
}
private byte[] doFinal(int encryptMode, SecretKey key, String iv, byte[] bytes) {
try {
cipher.init(encryptMode, key, new IvParameterSpec(hex(iv)));
return cipher.doFinal(bytes);
} catch (InvalidKeyException |
InvalidAlgorithmParameterException |
IllegalBlockSizeException |
BadPaddingException e) {
throw fail(e);
}
}
public static String base64(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
public static byte[] base64(String str) {
return Base64.getDecoder().decode(str);
}
protected static byte[] hex(String str) {
try {
return decodeHex(str.toCharArray());
} catch (Exception e) {
e.printStackTrace();
}
return new byte[0];
}
public static byte[] decodeHex(char[] data) throws Exception {
int len = data.length;
if ((len & 1) != 0) {
throw new Exception("Odd number of characters.");
} else {
byte[] out = new byte[len >> 1];
int i = 0;
for (int j = 0; j < len; ++i) {
int f = toDigit(data[j], j) << 4;
++j;
f |= toDigit(data[j], j);
++j;
out[i] = (byte)(f & 255);
}
return out;
}
}
protected static int toDigit(char ch, int index) throws Exception {
int digit = Character.digit(ch, 16);
if (digit == -1) {
throw new Exception("Illegal hexadecimal character " + ch + " at index " + index);
} else {
return digit;
}
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte)((Character.digit(s.charAt(i), 16) << 4) +
Character.digit(s.charAt(i + 1), 16));
}
return data;
}
private IllegalStateException fail(Exception e) {
return new IllegalStateException(e);
}
Decryption
params:
(same as in above java code)
code:
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
});
var decrypted = CryptoJS.AES.decrypt(
cipherParams,
key,
{ iv: CryptoJS.enc.Hex.parse(iv) });
var plaintext = decrypted.toString(CryptoJS.enc.Utf8);

Java aes encryption code, how to achieve through nodejs?

Java aes encryption code, how to achieve through nodejs?
I don't know how nodejs should implement the hexStringToBytes function, and aes decrypt
Source code:https://github.com/androider/mahuayingshi-java
public static String decryptHex(String str, String str2) {
str = "6cab6feb4e159bdbcb652ffd544a32db308bb2bd2b00f17c9a3d523c69159a0ed7589f602c30130ad2f0213226281767123cac47ca86c8f24511cec75a89b19227ecbae6b5f4ce564561098f2b12d2d4a6285ed146b0d2217924550c9e10256605077a3a4cff0be84e35627f004708f0";
str2 = "10737929DtXZcHh9";
String decrypt = null;
try {
decrypt = aesDecryptByBytes(hexStringToBytes(str), str2);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(decrypt);
return decrypt;
}
public static byte[] hexStringToBytes(String str) {
int length = str.length() / 2;
byte[] bArr = new byte[length];
for (int i = 0; i < length; i++) {
int i2 = i * 2;
bArr[i] = (byte) (((byte) (hexStr.indexOf(str.charAt(i2)) << 4)) | ((byte) hexStr.indexOf(str.charAt(i2 + 1))));
}
return bArr;
}
private static String aesDecryptByBytes(byte[] bArr, String str) throws Exception {
Cipher instance = Cipher.getInstance("AES/CBC/PKCS7Padding");
byte[] bytes = str.getBytes();
instance.init(2, new SecretKeySpec(bytes, "AES"), new IvParameterSpec(bytes));
return new String(instance.doFinal(bArr));
}

c# aes ctr no IV javascript [duplicate]

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I can't seem to find a nice clean example of using AES 128 bit encryption.
Does anyone have some sample code?
If you just want to use the built-in crypto provider RijndaelManaged, check out the following help article (it also has a simple code sample):
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx
And just in case you need the sample in a hurry, here it is in all its plagiarized glory:
using System;
using System.IO;
using System.Security.Cryptography;
namespace RijndaelManaged_Example
{
class RijndaelExample
{
public static void Main()
{
try
{
string original = "Here is some data to encrypt!";
// Create a new instance of the RijndaelManaged
// class. This generates a new key and initialization
// vector (IV).
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
myRijndael.GenerateKey();
myRijndael.GenerateIV();
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
// Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);
//Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Round Trip: {0}", roundtrip);
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
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("IV");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
I've recently had to bump up against this again in my own project - and wanted to share the somewhat simpler code that I've been using, as this question and series of answers kept coming up in my searches.
I'm not going to get into the security concerns around how often to update things like your Salt and Initialization Vector - that's a topic for a security forum, and there are some great resources out there to look at. This is simply a block of code to implement AesManaged in C#.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Your.Namespace.Security {
public static class Cryptography {
#region Settings
private static int _iterations = 2;
private static int _keySize = 256;
private static string _hash = "SHA1";
private static string _salt = "aselrias38490a32"; // Random
private static string _vector = "8947az34awl34kjq"; // Random
#endregion
public static string Encrypt(string value, string password) {
return Encrypt<AesManaged>(value, password);
}
public static string Encrypt<T>(string value, string password)
where T : SymmetricAlgorithm, new() {
byte[] vectorBytes = GetBytes<ASCIIEncoding>(_vector);
byte[] saltBytes = GetBytes<ASCIIEncoding>(_salt);
byte[] valueBytes = GetBytes<UTF8Encoding>(value);
byte[] encrypted;
using (T cipher = new T()) {
PasswordDeriveBytes _passwordBytes =
new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);
byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);
cipher.Mode = CipherMode.CBC;
using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes)) {
using (MemoryStream to = new MemoryStream()) {
using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) {
writer.Write(valueBytes, 0, valueBytes.Length);
writer.FlushFinalBlock();
encrypted = to.ToArray();
}
}
}
cipher.Clear();
}
return Convert.ToBase64String(encrypted);
}
public static string Decrypt(string value, string password) {
return Decrypt<AesManaged>(value, password);
}
public static string Decrypt<T>(string value, string password) where T : SymmetricAlgorithm, new() {
byte[] vectorBytes = GetBytes<ASCIIEncoding>(_vector);
byte[] saltBytes = GetBytes<ASCIIEncoding>(_salt);
byte[] valueBytes = Convert.FromBase64String(value);
byte[] decrypted;
int decryptedByteCount = 0;
using (T cipher = new T()) {
PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);
byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);
cipher.Mode = CipherMode.CBC;
try {
using (ICryptoTransform decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes)) {
using (MemoryStream from = new MemoryStream(valueBytes)) {
using (CryptoStream reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read)) {
decrypted = new byte[valueBytes.Length];
decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length);
}
}
}
} catch (Exception ex) {
return String.Empty;
}
cipher.Clear();
}
return Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount);
}
}
}
The code is very simple to use. It literally just requires the following:
string encrypted = Cryptography.Encrypt(data, "testpass");
string decrypted = Cryptography.Decrypt(encrypted, "testpass");
By default, the implementation uses AesManaged - but you could actually also insert any other SymmetricAlgorithm. A list of the available SymmetricAlgorithm inheritors for .NET 4.5 can be found at:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.symmetricalgorithm.aspx
As of the time of this post, the current list includes:
AesManaged
RijndaelManaged
DESCryptoServiceProvider
RC2CryptoServiceProvider
TripleDESCryptoServiceProvider
To use RijndaelManaged with the code above, as an example, you would use:
string encrypted = Cryptography.Encrypt<RijndaelManaged>(dataToEncrypt, password);
string decrypted = Cryptography.Decrypt<RijndaelManaged>(encrypted, password);
I hope this is helpful to someone out there.
Look at sample in here..
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=VS.100).aspx#Y2262
The example on MSDN does not run normally (an error occurs) because there is no initial value of Initial Vector(iv) and Key. I add 2 line code and now work normally.
More details see below:
using System.Windows.Forms;
using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace AES_TESTER
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
string original = "Here is some data to encrypt!";
MessageBox.Show("Original: " + original);
// Create a new instance of the RijndaelManaged
// class. This generates a new key and initialization
// vector (IV).
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
myRijndael.GenerateKey();
myRijndael.GenerateIV();
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
StringBuilder s = new StringBuilder();
foreach (byte item in encrypted)
{
s.Append(item.ToString("X2") + " ");
}
MessageBox.Show("Encrypted: " + s);
// Decrypt the bytes to a string.
string decrypted = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);
//Display the original data and the decrypted data.
MessageBox.Show("Decrypted: " + decrypted);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: {0}", ex.Message);
}
}
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.Zeros;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
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 (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.Zeros;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
Using AES or implementing AES? To use AES, there is the System.Security.Cryptography.RijndaelManaged class.
For a more complete example that performs key derivation in addition to the AES encryption, see the answer and links posted in Getting AES encryption to work across Javascript and C#.
EDIT
a side note: Javascript Cryptography considered harmful. Worth the read.
//Code to encrypt Data :
public byte[] encryptdata(byte[] bytearraytoencrypt, string key, string iv)
{
AesCryptoServiceProvider dataencrypt = new AesCryptoServiceProvider();
//Block size : Gets or sets the block size, in bits, of the cryptographic operation.
dataencrypt.BlockSize = 128;
//KeySize: Gets or sets the size, in bits, of the secret key
dataencrypt.KeySize = 128;
//Key: Gets or sets the symmetric key that is used for encryption and decryption.
dataencrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);
//IV : Gets or sets the initialization vector (IV) for the symmetric algorithm
dataencrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);
//Padding: Gets or sets the padding mode used in the symmetric algorithm
dataencrypt.Padding = PaddingMode.PKCS7;
//Mode: Gets or sets the mode for operation of the symmetric algorithm
dataencrypt.Mode = CipherMode.CBC;
//Creates a symmetric AES encryptor object using the current key and initialization vector (IV).
ICryptoTransform crypto1 = dataencrypt.CreateEncryptor(dataencrypt.Key, dataencrypt.IV);
//TransformFinalBlock is a special function for transforming the last block or a partial block in the stream.
//It returns a new array that contains the remaining transformed bytes. A new array is returned, because the amount of
//information returned at the end might be larger than a single block when padding is added.
byte[] encrypteddata = crypto1.TransformFinalBlock(bytearraytoencrypt, 0, bytearraytoencrypt.Length);
crypto1.Dispose();
//return the encrypted data
return encrypteddata;
}
//code to decrypt data
private byte[] decryptdata(byte[] bytearraytodecrypt, string key, string iv)
{
AesCryptoServiceProvider keydecrypt = new AesCryptoServiceProvider();
keydecrypt.BlockSize = 128;
keydecrypt.KeySize = 128;
keydecrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);
keydecrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);
keydecrypt.Padding = PaddingMode.PKCS7;
keydecrypt.Mode = CipherMode.CBC;
ICryptoTransform crypto1 = keydecrypt.CreateDecryptor(keydecrypt.Key, keydecrypt.IV);
byte[] returnbytearray = crypto1.TransformFinalBlock(bytearraytodecrypt, 0, bytearraytodecrypt.Length);
crypto1.Dispose();
return returnbytearray;
}
http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt
using System.Security.Cryptography;
using System.IO;
 
public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
public byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
{
byte[] decryptedBytes = null;
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
cs.Close();
}
decryptedBytes = ms.ToArray();
}
}
return decryptedBytes;
}
Try this code, maybe useful.
1.Create New C# Project and add follows code to Form1:
using System;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace ExampleCrypto
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string strOriginalData = string.Empty;
string strEncryptedData = string.Empty;
string strDecryptedData = string.Empty;
strOriginalData = "this is original data 1234567890"; // your original data in here
MessageBox.Show("ORIGINAL DATA:\r\n" + strOriginalData);
clsCrypto aes = new clsCrypto();
aes.IV = "this is your IV"; // your IV
aes.KEY = "this is your KEY"; // your KEY
strEncryptedData = aes.Encrypt(strOriginalData, CipherMode.CBC); // your cipher mode
MessageBox.Show("ENCRYPTED DATA:\r\n" + strEncryptedData);
strDecryptedData = aes.Decrypt(strEncryptedData, CipherMode.CBC);
MessageBox.Show("DECRYPTED DATA:\r\n" + strDecryptedData);
}
}
}
2.Create clsCrypto.cs and copy paste follows code in your class and run your code. I used MD5 to generated Initial Vector(IV) and KEY of AES.
using System;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
namespace ExampleCrypto
{
public class clsCrypto
{
private string _KEY = string.Empty;
protected internal string KEY
{
get
{
return _KEY;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_KEY = value;
}
}
}
private string _IV = string.Empty;
protected internal string IV
{
get
{
return _IV;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_IV = value;
}
}
}
private string CalcMD5(string strInput)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
StringBuilder strHex = new StringBuilder();
using (MD5 md5 = MD5.Create())
{
byte[] bytArText = Encoding.Default.GetBytes(strInput);
byte[] bytArHash = md5.ComputeHash(bytArText);
for (int i = 0; i < bytArHash.Length; i++)
{
strHex.Append(bytArHash[i].ToString("X2"));
}
strOutput = strHex.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
private byte[] GetBytesFromHexString(string strInput)
{
byte[] bytArOutput = new byte[] { };
if ((!string.IsNullOrEmpty(strInput)) && strInput.Length % 2 == 0)
{
SoapHexBinary hexBinary = null;
try
{
hexBinary = SoapHexBinary.Parse(strInput);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
bytArOutput = hexBinary.Value;
}
return bytArOutput;
}
private byte[] GenerateIV()
{
byte[] bytArOutput = new byte[] { };
try
{
string strIV = CalcMD5(IV);
bytArOutput = GetBytesFromHexString(strIV);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return bytArOutput;
}
private byte[] GenerateKey()
{
byte[] bytArOutput = new byte[] { };
try
{
string strKey = CalcMD5(KEY);
bytArOutput = GetBytesFromHexString(strKey);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return bytArOutput;
}
protected internal string Encrypt(string strInput, CipherMode cipherMode)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
byte[] bytePlainText = Encoding.Default.GetBytes(strInput);
using (RijndaelManaged rijManaged = new RijndaelManaged())
{
rijManaged.Mode = cipherMode;
rijManaged.BlockSize = 128;
rijManaged.KeySize = 128;
rijManaged.IV = GenerateIV();
rijManaged.Key = GenerateKey();
rijManaged.Padding = PaddingMode.Zeros;
ICryptoTransform icpoTransform = rijManaged.CreateEncryptor(rijManaged.Key, rijManaged.IV);
using (MemoryStream memStream = new MemoryStream())
{
using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Write))
{
cpoStream.Write(bytePlainText, 0, bytePlainText.Length);
cpoStream.FlushFinalBlock();
}
strOutput = Encoding.Default.GetString(memStream.ToArray());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
protected internal string Decrypt(string strInput, CipherMode cipherMode)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
byte[] byteCipherText = Encoding.Default.GetBytes(strInput);
byte[] byteBuffer = new byte[strInput.Length];
using (RijndaelManaged rijManaged = new RijndaelManaged())
{
rijManaged.Mode = cipherMode;
rijManaged.BlockSize = 128;
rijManaged.KeySize = 128;
rijManaged.IV = GenerateIV();
rijManaged.Key = GenerateKey();
rijManaged.Padding = PaddingMode.Zeros;
ICryptoTransform icpoTransform = rijManaged.CreateDecryptor(rijManaged.Key, rijManaged.IV);
using (MemoryStream memStream = new MemoryStream(byteCipherText))
{
using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Read))
{
cpoStream.Read(byteBuffer, 0, byteBuffer.Length);
}
strOutput = Encoding.Default.GetString(byteBuffer);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
}
}
You can use password from text box like key...
With this code you can encrypt/decrypt text, picture, word document, pdf....
public class Rijndael
{
private byte[] key;
private readonly byte[] vector = { 255, 64, 191, 111, 23, 3, 113, 119, 231, 121, 252, 112, 79, 32, 114, 156 };
ICryptoTransform EnkValue, DekValue;
public Rijndael(byte[] key)
{
this.key = key;
RijndaelManaged rm = new RijndaelManaged();
rm.Padding = PaddingMode.PKCS7;
EnkValue = rm.CreateEncryptor(key, vector);
DekValue = rm.CreateDecryptor(key, vector);
}
public byte[] Encrypt(byte[] byte)
{
byte[] enkByte= byte;
byte[] enkNewByte;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, EnkValue, CryptoStreamMode.Write))
{
cs.Write(enkByte, 0, enkByte.Length);
cs.FlushFinalBlock();
ms.Position = 0;
enkNewByte= new byte[ms.Length];
ms.Read(enkNewByte, 0, enkNewByte.Length);
}
}
return enkNeyByte;
}
public byte[] Dekrypt(byte[] enkByte)
{
byte[] dekByte;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, DekValue, CryptoStreamMode.Write))
{
cs.Write(enkByte, 0, enkByte.Length);
cs.FlushFinalBlock();
ms.Position = 0;
dekByte= new byte[ms.Length];
ms.Read(dekByte, 0, dekByte.Length);
}
}
return dekByte;
}
}
Convert password from text box to byte array...
private byte[] ConvertPasswordToByte(string password)
{
byte[] key = new byte[32];
for (int i = 0; i < passwprd.Length; i++)
{
key[i] = Convert.ToByte(passwprd[i]);
}
return key;
}
here is a neat and clean code to understand AES 256 algorithm implemented in C#
call Encrypt function as encryptedstring = cryptObj.Encrypt(username, "AGARAMUDHALA", "EZHUTHELLAM", "SHA1", 3, "#1B2c3D4e5F6g7H8", 256);
public class Crypt
{
public string Encrypt(string passtext, string passPhrase, string saltV, string hashstring, int Iterations, string initVect, int keysize)
{
string functionReturnValue = null;
// Convert strings into byte arrays.
// Let us assume that strings only contain ASCII codes.
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
// encoding.
byte[] initVectorBytes = null;
initVectorBytes = Encoding.ASCII.GetBytes(initVect);
byte[] saltValueBytes = null;
saltValueBytes = Encoding.ASCII.GetBytes(saltV);
// Convert our plaintext into a byte array.
// Let us assume that plaintext contains UTF8-encoded characters.
byte[] plainTextBytes = null;
plainTextBytes = Encoding.UTF8.GetBytes(passtext);
// First, we must create a password, from which the key will be derived.
// This password will be generated from the specified passphrase and
// salt value. The password will be created using the specified hash
// algorithm. Password creation can be done in several iterations.
PasswordDeriveBytes password = default(PasswordDeriveBytes);
password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashstring, Iterations);
// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
byte[] keyBytes = null;
keyBytes = password.GetBytes(keysize/8);
// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = default(RijndaelManaged);
symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;
// Generate encryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
ICryptoTransform encryptor = default(ICryptoTransform);
encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = default(MemoryStream);
memoryStream = new MemoryStream();
// Define cryptographic stream (always use Write mode for encryption).
CryptoStream cryptoStream = default(CryptoStream);
cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
// Start encrypting.
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
// Finish encrypting.
cryptoStream.FlushFinalBlock();
// Convert our encrypted data from a memory stream into a byte array.
byte[] cipherTextBytes = null;
cipherTextBytes = memoryStream.ToArray();
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert encrypted data into a base64-encoded string.
string cipherText = null;
cipherText = Convert.ToBase64String(cipherTextBytes);
functionReturnValue = cipherText;
return functionReturnValue;
}
public string Decrypt(string cipherText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
{
string functionReturnValue = null;
// Convert strings defining encryption key characteristics into byte
// arrays. Let us assume that strings only contain ASCII codes.
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
// encoding.
byte[] initVectorBytes = null;
initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = null;
saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
// Convert our ciphertext into a byte array.
byte[] cipherTextBytes = null;
cipherTextBytes = Convert.FromBase64String(cipherText);
// First, we must create a password, from which the key will be
// derived. This password will be generated from the specified
// passphrase and salt value. The password will be created using
// the specified hash algorithm. Password creation can be done in
// several iterations.
PasswordDeriveBytes password = default(PasswordDeriveBytes);
password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
byte[] keyBytes = null;
keyBytes = password.GetBytes(keySize / 8);
// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = default(RijndaelManaged);
symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;
// Generate decryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
ICryptoTransform decryptor = default(ICryptoTransform);
decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = default(MemoryStream);
memoryStream = new MemoryStream(cipherTextBytes);
// Define memory stream which will be used to hold encrypted data.
CryptoStream cryptoStream = default(CryptoStream);
cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
// Since at this point we don't know what the size of decrypted data
// will be, allocate the buffer long enough to hold ciphertext;
// plaintext is never longer than ciphertext.
byte[] plainTextBytes = null;
plainTextBytes = new byte[cipherTextBytes.Length + 1];
// Start decrypting.
int decryptedByteCount = 0;
decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert decrypted data into a string.
// Let us assume that the original plaintext string was UTF8-encoded.
string plainText = null;
plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
// Return decrypted string.
functionReturnValue = plainText;
return functionReturnValue;
}
}

Categories