I am using this function to encrypt data in my UWP project:
public string Encrypt(string text, string key)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
byte[] sessionKey = Encoding.UTF8.GetBytes(key);
Aes myAes = Aes.Create();
myAes.Mode = CipherMode.ECB;
myAes.KeySize = 128;
myAes.Key = sessionKey;
myAes.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = myAes.CreateEncryptor();
buffer = encryptor.TransformFinalBlock(buffer, 0, buffer.Length);
return Convert.ToBase64String (buffer);
}
But upon decrypting the data returned from Encrypt() , I get a different result (not equal to the text parameter of Encrypt() ). I am using the following code:
public string Decrypt(string text, string key)
{
byte[] buffer = Convert.FromBase64String(text);
byte[] sessionKey = Encoding.UTF8.GetBytes(key);
Aes myAes = Aes.Create();
myAes.Mode = CipherMode.ECB;
myAes.KeySize = 128;
myAes.Key = sessionKey;
myAes.Padding = PaddingMode.PKCS7;
ICryptoTransform decryptor = myAes.CreateDecryptor();
buffer = decryptor.TransformFinalBlock(buffer, 0, buffer.Length);
return Convert.ToBase64String(buffer);
}
I am using the same key for both encryption and decryption
UPDATE:
text parameter passed to Encrypt() : 450131283::0300DC98050044C406000100040052C40100626B02007E810900660F
Return text from Encrypt():
"lzkPu35Hq7j52IiMWRYSS6j7Vg84abVmhXmNpSxHShJDTbOqkZRFtsPZkEzTsjgRT4MzRHCQUS6MCiq1e5JCune4bZZi1nxxwHtEjZLKZ9E="
the same (above) value I pass to the Decrypt() method and I get the following:
"NDUwMTMxMjgzOjowMzAwREM5ODA1MDA0NEM0MDYwMDAxMDAwNDAwNTJDNDAxMDA2MjZCMDIwMDdFODEwOTAwNjYwRg=="
The problem is what you're doing with the end of the decryption:
return Convert.ToBase64String(buffer);
You actually want to convert the decrypted binary data back into a string in a way that mirrors the original way you converted it from a string into plaintext binary data, so you want:
return Encoding.UTF8.GetString(buffer);
This sort of problem is usually best addressed by looking at every step in the transformation chain each direction, and make sure that they're balanced. So it should look like this:
Text
(Encode with UTF-8)
Non-encrypted binary data
(Encrypt)
Encrypted binary data
(Convert to base64)
Encrypted data as base64 text
(Store or whatever...)
Encrypted data as base64 text
(Convert from base64)
Encrypted binary data
(Decrypt)
Non-encrypted binary data
(Decode with UTF-8)
Text
Where I've got "decode with UTF-8" you've got "Convert to base64" so the decoding steps don't match the encoding steps.
Related
Here is the code used to encrypt in coldfusion
<cfset strBase64Value = encrypt(strValue,24 character key,AES) />
It is generating encrypted values like 714FEA9A9A2184769CA49D5133F08580 which seems odd to me considering it is only uppercase and numbers.
What C# library should I use to properly decrypt it ?
Also looking at this information, it seems that by default it uses the UUEncode algorithm to encode.
Should I ask the encrypter to use Base64 as encoding parameter ?
It is generating encrypted values like 714FEA9A9A2184769CA49D5133F08580
Then they are using "Hex", not the default "UUEncode". Either "hex" or "base64" is fine. As long as you both agree upon the encoding, it does not really matter.
You can use RijndaelManaged to decrypt the strings. However, the default encryption settings for ColdFusion and C# differ slightly. With the encrypt function:
"AES" is short for "AES/ECB/PKCS5Padding"
"ECB" mode does not use an IV
Key strings are always base64 encoded
NB: Despite the name difference, for the SUN provider, PKCS5Padding (CF/Java) corresponds to PaddingMode.PKCS7 (C#). As mentioned in this thread, the "... SUN provider in Java indicate[s] PKCS#5 where PKCS#7 should be used - "PKCS5Padding" should have been "PKCS7Padding". This is a legacy from the time that only 8 byte block ciphers such as (triple) DES symmetric cipher were available."
So you need to ensure your C# settings are adjusted to match. With that in mind, just decode the encrypted text from hex and the key string from base64. Using the slightly ugly example in the API, just adjust the algorithm settings to match those used by the encrypt() function:
Encrypt with ColdFusion
<cfscript>
plainText = "Nothing to see";
// 128 bit key base64 encoded
keyInBase64 = "Y25Aju8H2P5DR8mY6B0ezg==";
// "AES" is short for "AES/ECB/PKCS5Padding"
encryptedText = encrypt(plainText, keyInBase64, "AES", "hex");
WriteDump( encryptedText );
// result: 8889EDF02F181158AAD902AB86C63951
</cfscript>
Decrypt with C#
byte[] bytes = SomeMethodToConvertHexToBytes( encryptedText );
byte[] key = Convert.FromBase64String( keyInBase64 );
string decryptedText = null;
using (RijndaelManaged algorithm = new RijndaelManaged())
{
// initialize settings to match those used by CF
algorithm.Mode = CipherMode.ECB;
algorithm.Padding = PaddingMode.PKCS7;
algorithm.BlockSize = 128;
algorithm.KeySize = 128;
algorithm.Key = key;
ICryptoTransform decryptor = algorithm.CreateDecryptor();
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
decryptedText = srDecrypt.ReadToEnd();
}
}
}
}
Console.WriteLine("Encrypted String: {0}", encryptedText);
Console.WriteLine("Decrypted String: {0}", decryptedText);
Keep in mind you can (and probably should) adjust the settings, such as using the more secure CBC mode instead of ECB. You just need to coordinate those changes with the CF developer.
If anyone had similar problem with JAVA I just implemented encryption and decryption of string previously encrypted/decrypted in coldfusion with "Hex" and "tripledes". Here is my code:
private static final String PADDING = "DESede/ECB/PKCS5Padding";
private static final String UTF_F8 = "UTF-8";
private static final String DE_SEDE = "DESede";
private String secretKey;
public String encrypt(String message) throws Exception {
secretKey = getSecretKey();
final byte[] secretBase64Key = Base64.decodeBase64(secretKey);
final SecretKey key = new SecretKeySpec(secretBase64Key, DE_SEDE);
final Cipher cipher = Cipher.getInstance(PADDING);
cipher.init(Cipher.ENCRYPT_MODE, key);
final byte[] plainTextBytes = message.getBytes();
final byte[] cipherText = cipher.doFinal(plainTextBytes);
return Hex.encodeHexString(cipherText);
}
public String decrypt(String keyToDecrypt) throws Exception {
secretKey = getSecretKey();
byte[] message = DatatypeConverter.parseHexBinary(keyToDecrypt);
final byte[] secretBase64Key = Base64.decodeBase64(secretKey);
final SecretKey key = new SecretKeySpec(secretBase64Key, DE_SEDE);
final Cipher decipher = Cipher.getInstance(PADDING);
decipher.init(Cipher.DECRYPT_MODE, key);
final byte[] plainText = decipher.doFinal(message);
return new String(plainText, UTF_F8);
}
I'm implementing a C# application that needs to save 10 IP addresses in it. So i think it is resource wasting if I integrate a database in to the application. I cannot use XML or text file because those addresses needs to be secure. I sow a suggestion to implement my own file format and use it.1. Is there any suggestion instead implement separate file format2.if there isn't any how to implement new file format and what is the best
Store it in a file and encrypt the file so that it is not readable by other programs.
You can either save details an sqlite database or in a file,
if you want to keep things as private then encrypt the file
Apply Salt on it and save them in Text File or Xml, when its encrypted there is no danger of being data not safe.
See this sample:
using System.Security.Cryptography;
public static string EncodePasswordToBase64(string password)
{ byte[] bytes = Encoding.Unicode.GetBytes(password);
byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(bytes);
return Convert.ToBase64String(inArray);
}
Hashing is applied using SHA1 to envcrypt the string in this method.
Encrypt the strings using a strong encryption. here 2 methods i like to use. It strongly encrypt and also add salt to it.
public static string EncryptString(string sData, string sKey)
{
// instance of the Rihndael.
RijndaelManaged RijndaelManagedCipher = new RijndaelManaged();
// string to byte array.
byte[] UnicodeText = System.Text.Encoding.Unicode.GetBytes(sData);
// adign dirt to the string to make it harder to guess using a dictionary attack.
byte[] Dirty = Encoding.ASCII.GetBytes(sKey.Length.ToString());
// The Key will be generated from the specified Key and dirt.
PasswordDeriveBytes FinalKey = new PasswordDeriveBytes(sKey, Dirty);
// Create a encryptor from the existing FinalKey bytes.
ICryptoTransform Encryptor = RijndaelManagedCipher.CreateEncryptor(FinalKey.GetBytes(32), FinalKey.GetBytes(16));
// Create a MemoryStream that is going to hold the encrypted bytes
MemoryStream memoryStream = new MemoryStream();
// Create a CryptoStream
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
// write the encryption
cryptoStream.Write(UnicodeText, 0, UnicodeText.Length);
// write final blocks to the memory stream
cryptoStream.FlushFinalBlock();
// Convert to byte array the encrypted data
byte[] CipherBytes = memoryStream.ToArray();
// Close streams.
memoryStream.Close();
cryptoStream.Close();
// Convert to byte array to string
string EncryptedData = Convert.ToBase64String(CipherBytes);
// Return the encrypted string
return EncryptedData;
}
public static string DecryptString(string sData, string sKey)
{
// instance of rijndael
RijndaelManaged RijndaelCipher = new RijndaelManaged();
// convert to byte aray the encrypted data
byte[] EncryptedData = Convert.FromBase64String(sData);
// add dirt to the key like when encrypthing
byte[] Dirty = Encoding.ASCII.GetBytes(sKey.Length.ToString());
// get the finalkey o be used
PasswordDeriveBytes FinalKey = new PasswordDeriveBytes(sKey, Dirty);
// Create a decryptor with the key
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(FinalKey.GetBytes(32), FinalKey.GetBytes(16));
// load to memory stream the encrypted data
MemoryStream memoryStream = new MemoryStream(EncryptedData);
// Create a CryptoStream on the memory stream holding the data
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
// Length is unknown but need placeholder big enought for decrypted data
// we know the decrypted version cannot ever be longer than the crypted version
// since we added bunch of garbage to it so the length of encrypted data is safe to use
byte[] UnicodeText = new byte[EncryptedData.Length];
// Start decrypting
int DecryptedCount = cryptoStream.Read(UnicodeText, 0, UnicodeText.Length);
//close streams
memoryStream.Close();
cryptoStream.Close();
// load decrypted data to string
string DecryptedData = Encoding.Unicode.GetString(UnicodeText, 0, DecryptedCount);
// Return decrypted string
return DecryptedData;
}
Adding to this
now simply make a class like
public class Settings
{
public const string EncryptionKey = "somekey";
public List<string> IP = new List<string>();
public string getClassEncrypted()
{
return EncryptString(new JavaScriptSerializer().Serialize(this), EncryptionKey);
}
public Settings getClassDecrypted(string sClassEcrypted)
{
return new JavaScriptSerializer().Deserialize<Settings>(DecryptString(sClassEcrypted, EncryptionKey));
}
}
one the Ips are set in just write to a file the Settings.getClassEncrypted();
and then when it's time to get back the values only read the text file and load back up with something like this :
string sFileText = ...; // from the file saved
var setting = new Settings.getClassDecrypted(sFileText);
now you've got all classes you need to do it. And the class is even serialized
I am getting length of the string wrong after using the following Decryption Method.
public static string DecryptRJ256(string prm_key, string prm_iv, string prm_text_to_decrypt) {
string sEncryptedString = prm_text_to_decrypt;
RijndaelManaged myRijndael = new RijndaelManaged();
myRijndael.Padding = PaddingMode.Zeros;
myRijndael.Mode = CipherMode.CBC;
myRijndael.KeySize = 256;
myRijndael.BlockSize = 256;
byte[] key = Encoding.ASCII.GetBytes(prm_key);
byte[] IV = Encoding.ASCII.GetBytes(prm_iv);
ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);
byte[] sEncrypted = Convert.FromBase64String(sEncryptedString);
byte[] fromEncrypt = new byte[sEncrypted.Length];
MemoryStream msDecrypt = new MemoryStream(sEncrypted);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
return (Encoding.ASCII.GetString(fromEncrypt));
}
For example:
string ID = "yUFYhclPyPubnhMZ+SHJb1wrt44pao3B82jdbL1ierM=";
string finalID = DecryptRJ256(sKy, sIV, ID);
Response.Write(finalID); \\200905410 (**this is correct**)
Response.Write(finalID.Length); \\32 (**this should be 9**)
What am I doing wrong?
You are using zero padding. This pads the message with zero bytes until it reaches the block size (32 bytes in your case). Since zero padding is ambiguous (can't distinguish between an input that ended with zero bytes and the padding), .net doesn't remove it automatically.
So you have two choices:
Use PKCS7 padding for both encryption and decryption (that's what I recommend)
Manually strip all terminal zero bytes from the decrypted plaintext.
Your crypto isn't good either:
Keys and IVs should be binary, not ASCII (use base64 encoding here)
Using ASCII on the plaintext silently corrupts unicode characters - Use utf-8 instead
You need a new random IV for each encryption call and need to read it back during decryption
You should add a MAC, else active attacks (such as padding oracles) can often break it.
Use TransformFinalBlock instead of those memory streams.
Why use Rijndael256 over AES?
When I compiled this with symmetric decryptor object with the current Key, that is without key and IV, I get this as finalID.
???hV?9-2O?o?????}yl?????N?W
exactly 32 characters.
Refining the key and IV would help. I am not sure, but hope this might help.
I am trying to encrypt and decrypt a file with the rijndael algorythm, but i have been getting the error "Length of the data to encrypt is invalid.". I am able to encrypt the file, but i can't decrypt it. This is my decryption function;
public static byte[] Decrypt(byte[] toEncryptArray)
{
byte[] keyArray = UTF8Encoding.UTF8.GetBytes("-key-");
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateDecryptor();
return cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
}
I honestly have no idea what i am doing wrong, as i can encrypt it perfectly fine. The file i am trying to decrypt is 11 kb.
You should be using the CryptoStream object, which will automatically call the correct ICryptoTransform.TransformFinalBlock and ICryptoTransform.TransformBlock methods.
You haven't posted the encryption code but check that the Padding mode the same (i.e. PaddingMode.PKCS7) and the initiation vector is set to the same string.
C#
string keystr = "0123456789abcdef0123456789abcdef";
string plainText = "www.bouncycastle.org";
RijndaelManaged crypto = new RijndaelManaged();
crypto.KeySize = 128;
crypto.Mode = CipherMode.CBC;
crypto.Padding = PaddingMode.PKCS7;
crypto.Key = keystr.ToCharArray().Select(c=>(byte)c).ToArray();
// get the IV and key for writing to a file
byte[] iv = crypto.IV;
byte[] key = crypto.Key;
// turn the message into bytes
// use UTF8 encoding to ensure that Java can read in the file properly
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText.ToCharArray());
// Encrypt the Text Message using AES (Rijndael) (Symmetric algorithm)
ICryptoTransform sse = crypto.CreateEncryptor();
MemoryStream encryptedFs = new MemoryStream();
CryptoStream cs = new CryptoStream(encryptedFs, sse, CryptoStreamMode.Write);
try
{
cs.Write(plainBytes, 0, plainBytes.Length);
cs.FlushFinalBlock();
encryptedFs.Position = 0;
string result = string.Empty;
for (int i = 0; i < encryptedFs.Length; i++)
{
int read = encryptedFs.ReadByte();
result += read.ToString("x2");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
encryptedFs.Close();
cs.Close();
}
}
Java:
private String key = "0123456789abcdef0123456789abcdef";
private String plainText = "www.bouncycastle.org";
cipherText = performEncrypt(Hex.decode(key.getBytes()), plainText);
private byte[] performEncrypt(byte[] key, String plainText)
{
byte[] ptBytes = plainText.getBytes();
final RijndaelEngine rijndaelEngine = new RijndaelEngine();
cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(rijndaelEngine));
String name = cipher.getUnderlyingCipher().getAlgorithmName();
message("Using " + name);
byte[]iv = new byte[16];
final KeyParameter keyParameter = new KeyParameter(key);
cipher.init(true, keyParameter);
byte[] rv = new byte[cipher.getOutputSize(ptBytes.length)];
int oLen = cipher.processBytes(ptBytes, 0, ptBytes.length, rv, 0);
try
{
cipher.doFinal(rv, oLen);
}
catch (CryptoException ce)
{
message("Ooops, encrypt exception");
status(ce.toString());
}
return rv;
}
C# produces: ff53bc51c0caf5de53ba850f7ba08b58345a89a51356d0e030ce1367606c5f08
java produces: 375c52fd202696dba679e57f612ee95e707ccb05aff368b62b2802d5fb685403
Can somebody help me to fix my code?
In the Java code, you do not use the IV.
I am not savvy enough in C# to help you directly, but I can give some information.
Rijndael, aka "the AES", encrypts blocks of 16 bytes. To encrypt a long message (e.g. your test message, when encoding, is 20 bytes long), Rijndael must be invoked several times, with some way to chain the invocations together (also, there is some "padding" to make sure that the input length is a multiple of 16). The CBC mode performs such chaining.
In CBC, each block of data is combined (bitwise XOR) with the previous encrypted block prior to being itself encrypted. Since the first block of data has no previous block, we add a new conventional "zero-th block" called the IV. The IV should be chosen as 16 random bytes. The decrypting party will need the IV. The IV needs not be secret (that's the difference between the IV and the key) so it is often transmitted along the message.
In your Java code, you do not specify the IV, you just create a variable called iv and do not use it. So the Rijndael implementation is on its own for that. Chances are that it generated a random IV. Similarly, you do not give an IV to the Rijndael implementation in the C# code. So it is quite plausible that there again a random IV was selected. But not the same than the one in the Java code, hence the distinct results.
(Note: you 20-byte input string is padded to 32 bytes. You give two "results" in hexadecimal, of length 32 bytes each. This is coherent but means that those results do not include the IV -- otherwise they would be 48-byte long.)
I think the algorithm is built in slighty different way and/or the salt key is interpered in different way.