Decoding And Encoding Strings - HardCoded KEY for Symmetric Algorithms - c#

i wrote the below class for encoding and decoding string data (Symmetric Algorithm With One Key):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace MyProject.Classes
{
public static class SymmetricEncryption
{
private const string MyKey = "bla bla bla";
private static string _AlgorithmName;
public static string AlgorithmName
{
get { return _AlgorithmName; }
set { _AlgorithmName = value; }
}
public static string EncryptData(string ClearData)
{
// Convert string ClearData to byte array
byte[] ClearData_byte_Array = Encoding.UTF8.GetBytes(ClearData);
// Now Create The Algorithm
SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
Algorithm.Key = Encoding.UTF8.GetBytes(MyKey);
// Encrypt information
MemoryStream Target = new MemoryStream();
// Append IV
Algorithm.GenerateIV();
Target.Write(Algorithm.IV, 0, Algorithm.IV.Length);
// Encrypt Clear Data
CryptoStream cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(ClearData_byte_Array, 0, ClearData_byte_Array.Length);
cs.FlushFinalBlock();
// Output
byte[] Target_byte_Array = Target.ToArray();
string Target_string = Convert.ToBase64String(Target_byte_Array);
return Target_string;
}
public static string DecryptData(string EncryptedData)
{
byte[] EncryptedData_byte_Array = Convert.FromBase64String(EncryptedData);
// Now Create The Algorithm
SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
Algorithm.Key = Encoding.UTF8.GetBytes(MyKey);
// Decrypt information
MemoryStream Target = new MemoryStream();
// Read IV
int ReadPos = 0;
byte[] IV = new byte[Algorithm.IV.Length];
Array.Copy(EncryptedData_byte_Array, IV, IV.Length);
Algorithm.IV = IV;
ReadPos += Algorithm.IV.Length;
// Decrypt Encrypted Data
CryptoStream cs = new CryptoStream(Target, Algorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(EncryptedData_byte_Array, ReadPos, EncryptedData_byte_Array.Length - ReadPos);
cs.FlushFinalBlock();
// Output
byte[] Target_byte_Array = Target.ToArray();
string Target_string = Encoding.UTF8.GetString(Target_byte_Array);
return Target_string;
}
}
}
and usage like below :
protected void Page_Load(object sender, EventArgs e)
{
SymmetricEncryptionUtility.AlgorithmName = "TripleDES";
Response.Write(SymmetricEncryptionUtility.EncryptData("1234-4567-8910-2345"));
}
i have some problem about MyKey -> how can we have hard coded key for Symmetric Algorithms and use it in the upper class ?
the upper codes ERROR is like below :
Server Error in '/' Application.
Specified key is not a valid size for this algorithm.
Description: An unhandled exception occurred during the
execution of the current web request. Please review the stack trace
for more information about the error and where it originated in the
code.
Exception Details:
System.Security.Cryptography.CryptographicException: Specified key is
not a valid size for this algorithm.
how can i fix this error ?
thanks in advance

You can use System.Security.Cryptography.Rfc2898DeriveBytes to securely generate the correct number of bytes for your key based on a string password and byte[] salt:
var helper = new Rfc2898DeriveBytes(password, salt);
algorithm.Key = helper.GetBytes(algorithm.KeySize / 8);
For more information about Rfc2898DeriveBytes and how to use it, check out its page on MSDN.

Read the error and look at the documentation for TripleDES.Key:
This algorithm supports key lengths from 128 bits to 192 bits in increments of 64 bits.
That means for example
private const string MyKey = "bla bla bla blah";
would work.
You didn't ask about this, but I'm not sure creating this class as static is a good idea. If you used it from two different places in your code, it could result in unexpected results, because AlgorithmName is static.
Also, I don't think it makes sense to have a constant key but variable algorithm, especially since different algorithms require keys of different lengths.

Related

Getting error Length of the data to decrypt is invalid [duplicate]

I am working in a C# application. We have common methods to store data on a file. These methods encrypt the data and store them on the file system. when we need the data, ReadData method decrypts the data and returns me plain text.
This code works fine in normal cases if size of the text in small. but for a example text given below, the decryption code is throwing exception - length of the data to decrypt is invalid.
The exception occurs at line
// close the CryptoStream
x_cryptostream.Close();
I tried different ways but no luck. Can some pls help.
Why am I encrypting already encrypted data - I am just trying to store in a file using common method of the huge application. The common methods storedata(key,data) nad readdata(key) do the encryption/decryption I can't avoid.
public static byte[] Decrypt(byte[] ciphertext, string Key, string IV)
{
byte[] k = Encoding.Default.GetBytes(Key);
byte[] iv = Encoding.Default.GetBytes(IV);
// create the encryption algorithm
SymmetricAlgorithm x_alg = SymmetricAlgorithm.Create("Rijndael");
x_alg.Padding = PaddingMode.PKCS7;
// create an ICryptoTransform that can be used to decrypt data
ICryptoTransform x_decryptor = x_alg.CreateDecryptor(k, iv);
// create the memory stream
MemoryStream x_memory_stream = new MemoryStream();
// create the CryptoStream that ties together the MemoryStream and the
// ICryptostream
CryptoStream x_cryptostream = new CryptoStream(x_memory_stream,
x_decryptor, CryptoStreamMode.Write);
// write the ciphertext out to the cryptostream
x_cryptostream.Write(ciphertext, 0, ciphertext.Length);
// close the CryptoStream
x_cryptostream.Close();
// get the plaintext from the MemoryStream
byte[] x_plaintext = x_memory_stream.ToArray();
Below is the code of encrypt method.
public static byte[] Encrypt(string strplain, string Key, string IV)
{
byte[] k = Encoding.Default.GetBytes(Key);
byte[] iv = Encoding.Default.GetBytes(IV);
byte[] plaintext = Encoding.Default.GetBytes(strplain);
// create the encryption algorithm
SymmetricAlgorithm x_alg = SymmetricAlgorithm.Create("Rijndael");
x_alg.Padding = PaddingMode.PKCS7;
// create an ICryptoTransform that can be used to encrypt data
ICryptoTransform x_encryptor = x_alg.CreateEncryptor(k, iv);
// create the memory stream
MemoryStream x_memory_stream = new MemoryStream();
// create the CryptoStream that ties together the MemoryStream and
// the ICryptostream
CryptoStream x_cryptostream = new CryptoStream(x_memory_stream,
x_encryptor, CryptoStreamMode.Write);
// write the plaintext out to the cryptostream
x_cryptostream.Write(plaintext, 0, plaintext.Length);
// close the CryptoStream
x_cryptostream.Close();
// get the ciphertext from the MemoryStream
byte[] x_ciphertext = x_memory_stream.ToArray();
// close memory stream
x_memory_stream.Close();
// convert from array to string
string cipher_Tx = Encoding.Default.GetString(x_ciphertext,
0, x_ciphertext.Length);
x_encryptor.Dispose();
x_alg.Clear();
byte[] cipher = Encoding.Default.GetBytes(cipher_Tx);
return cipher;
}
Your problem is string cipher_Tx = Encoding.Default.GetString(x_ciphertext, 0, x_ciphertext.Length);.
x_ciphertext is not a valid byte representation of text, it has many unpresentable characters and when you do your byte[] to string conversion you are losing information. The correct way to do it is use a string format that is designed to represent binary data using something like Convert.ToBase64String(byte[]) and Convert.FromBase64String(string).
string cipher_Tx = Convert.ToBase64String(x_ciphertext)
x_encryptor.Dispose();
x_alg.Clear();
byte[] cipher = Convert.FromBase64String(cipher_Tx)
That being said, there is a lot of other "odd" things about your code, for example you don't use using statements and you really should. Also that whole conversion to string and back is totally unnecessary, just return x_ciphertext. There may be other problems with the code too (like where did the strings for Key and IV come from) and many other best practices (like you should be generating a random IV and writing it out in to the output and the key should be generated using a key derivation function not straight from user text), but I stopped checking after I found the string conversion issue.
Your code above works as long as the key and iv used to decrypt match the key and iv used to encrypt. Try this:
byte[] test = new byte[1000000];
for (int i = 0; i < 256; i++)
{
test[i] = (byte)i;
}
var ciphertext = Encrypt(Encoding.Default.GetString(test), "0000000000000000", "0000000000000000");
byte[] check = Decrypt(ciphertext, "0000000000000000", "0000000000000000");
for (int i = 0; i < 256; i++)
{
Debug.Assert(check[i] == (byte)i, "round trip");
}
As you can see, one million bytes encrypt and decrypt just fine with your code, so I don't think it has anything to do with data size.
However, change the IV like this:
byte[] check = Decrypt(ciphertext, "0000000000000000", "000000000000000X"); // note X
and the Debug.Assert will fire -- the decryption will not match. However, x_cryptostream.Close() succeeds.
Next, try changing the key like this:
byte[] check = Decrypt(ciphertext, "000000000000000X", "0000000000000000"); // note X
Now, x_cryptostream.Close() will fail with a CryptographicException, probably, "Padding is invalid and cannot be removed."
Corrupting the key will cause the decryption to fail, and x_cryptostream.Close() to fail.
I think the problem is in your saving and later restoring the key bytes.
BTW: Hopefully you are using the full binary range of the key, and not basing it only on ASCII characters, otherwise you don't really have a strong key.

AES decryption only producing part of the answer C#

I'm trying to learn cyber security and this is the very first thing I've done on it. I'm using this MSDN document ( https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rfc2898derivebytes?redirectedfrom=MSDN&view=netcore-3.1 ) and it partly works. I assume it's encrypting it fine as when it comes to the decryption some of the original data is there but some is lost. The data that is being encrypted is a class that has been formatted into a JSON string( I don't think this is relevant as it's still a string being encrypted).
But once it's been encrypted and decrypted it turns out like this:
I've ran this code and compared the results 5+ times and it's always: the start is wrong, username is partly right, password is always right and loginkey is partly right. So the error is recurring and always in the same spot.
Information you should know, the data get's encrypted and saved to a .txt file. The programme will run again and it will try and decrypted it. The Salt and password are saved on another file and those are read and used in the decryption.
There is a similar question on stackoverflow but the answer just says to use Rijndael(so not really an answer), this code is for me to learn and want an answer that isn't 4 lines long.
Code if curious(but it's basically the same as the MSDN document):
Encryption:
static void EncryptFile()
{
string pwd1 = SteamID;//steamID is referring to account ID on Valve Steam
using (RNGCryptoServiceProvider rngCsp = new
RNGCryptoServiceProvider())
{
rngCsp.GetBytes(salt1); //salt1 is a programme variable and will get saved to a file
}
SecureData File = new SecureData(_UserName,_PassWord,_LoginKey);
string JsonFile = JsonConvert.SerializeObject(File); //puts the class into Json format
int myIterations = 1000; //not needed
try
{
Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes(pwd1, salt1,
myIterations);
Aes encAlg = Aes.Create(); // This might be the issue as AES will be different when you decrypt
encAlg.Key = k1.GetBytes(16);
MemoryStream encryptionStream = new MemoryStream();
CryptoStream encrypt = new CryptoStream(encryptionStream,
encAlg.CreateEncryptor(), CryptoStreamMode.Write);
byte[] utfD1 = new System.Text.UTF8Encoding(false).GetBytes(
JsonFile); //encrypt Data
encrypt.Write(utfD1, 0, utfD1.Length);
encrypt.FlushFinalBlock();
encrypt.Close();
byte[] edata1 = encryptionStream.ToArray();
k1.Reset();
System.IO.File.WriteAllBytes(SecureFile, edata1); //writes encrypted data to file
}
catch (Exception e)
{
Console.WriteLine("Error: ", e);
}
}
Decryption:
static void DecryptFile()
{
string pwd1 = SteamID;
byte[] edata1;
try
{
edata1 = System.IO.File.ReadAllBytes(SecureFile); //reads the file with encrypted data on it
Aes encAlg = Aes.Create(); //I think this is the problem as the keyvalue changes when you create a new programme
Rfc2898DeriveBytes k2 = new Rfc2898DeriveBytes(pwd1, salt1); //inputs from last time carry over
Aes decAlg = Aes.Create();
decAlg.Key = k2.GetBytes(16);
decAlg.IV = encAlg.IV;
MemoryStream decryptionStreamBacking = new MemoryStream();
CryptoStream decrypt = new CryptoStream(
decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write);
decrypt.Write(edata1, 0, edata1.Length);
decrypt.Flush();
decrypt.Close();
k2.Reset();
string data2 = new UTF8Encoding(false).GetString(
decryptionStreamBacking.ToArray());//decrypted data
SecureData items = JsonConvert.DeserializeObject<SecureData>(data2); //reformat it out of JSon(Crashes as format isn't accepted)
_UserName = items.S_UserName;
_PassWord = items.S_Password;
_LoginKey = items.S_LoginKey;
}
catch (Exception e)
{
Console.WriteLine("Error: ", e);
NewLogin();
}
}
Class Struct:
class SecureData
{
public string S_UserName { get; set; } //These are variables that are apart of Valve steam Login process
public string S_Password { get; set; }
public string S_LoginKey { get; set; }
public SecureData(string z, string x, string y)
{
S_UserName = z;
S_Password = x;
S_LoginKey = y;
}
}
The problem is caused by different IVs for encryption and decryption. For a successful decryption the IV from the encryption must be used.
Why are different IVs applied? When an AES instance is created, a random IV is implicitly generated. Two different AES instances therefore mean two different IVs. In the posted code, different AES instances are used for encryption and decryption. Although the reference encAlg used in the decryption has the same name as that of the encryption, the referenced instance is a different one (namely an instance newly created during decryption). This is different in the Microsoft example. There, the IV of the encryption is used in the decryption: decAlg.IV = encAlg.IV, where encAlg is the AES instance with which the encryption was performed.
The solution is to store the IV from the encryption in the file so that it can be used in the decryption. The IV is not secret and is usually placed before the ciphertext:
Necessary changes in EncryptFile:
...
byte[] utfD1 = new System.Text.UTF8Encoding(false).GetBytes(JsonFile);
encryptionStream.Write(encAlg.IV, 0, encAlg.IV.Length); // Write the IV
encryptionStream.Flush();
encrypt.Write(utfD1, 0, utfD1.Length);
...
Necessary changes in DecryptFile:
...
edata1 = System.IO.File.ReadAllBytes(SecureFile);
byte[] iv = new byte[16]; // Separate IV and ciphertext
byte[] ciphertext = new byte[edata1.Length - iv.Length];
Array.Copy(edata1, 0, iv, 0, iv.Length);
Array.Copy(edata1, iv.Length, ciphertext, 0, ciphertext.Length);
...
Aes encAlg = Aes.Create(); // Remove this line
...
decAlg.IV = iv; // Use the separated IV
...
decrypt.Write(ciphertext, 0, ciphertext.Length); // Use the separated ciphertext
A few remarks:
For each encryption a new, random salt should be generated and concatenated with the ciphertext analogous to the IV. During decryption, the salt can then be determined analogous to IV. Consider additionally RFC8018, sec 4.1.
The iteration count slows down the derivation of the key, which should make an attack by repeated attempts more difficult. Therefore the value should be as large as possible. Consider additionally RFC8018, sec 4.2.
Authentication data (i.e. passwords) are not encrypted, but hashed, here.

Rijndael encrypter: Getting empty byte[]. Not encrypting anything

Good evening!
I'm trying to implement an encrypter using Rijndael algorithm and Rijndael class in c#. I tried to follow (not doing exactly the same code) the link bellow, but the problem is given a string to be encrypted I'm not getting any result. I'm no getting any error message too.
https://learn.microsoft.com/pt-br/dotnet/api/system.security.cryptography.rijndael?view=netframework-4.8
CryptDecrypt.cs
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace RijndaelAlgorithm {
public class CryptDecrypt {
private Byte[] iv;
private Byte[] key;
public CryptDecrypt(String key) {
iv = new Byte[] {21, 10, 21, 251, 132, 76, 121, 27, 210, 81, 215, 99, 14, 235, 11, 75};
this.key = Encoding.ASCII.GetBytes(key);
}
public String encryptMsg(String originalMsg) {
byte[] encryptedMsg;
Rijndael rijAlg = Rijndael.Create();
rijAlg.Key = formatKey();
rijAlg.IV = iv;
MemoryStream msEncrypt = new MemoryStream();
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
StreamWriter swEncrypt = new StreamWriter(csEncrypt);
swEncrypt.Write(originalMsg);
encryptedMsg = msEncrypt.ToArray();
Console.WriteLine("encryptedMsg.Length: " + encryptedMsg.Length);
return Convert.ToBase64String(encryptedMsg, 0, encryptedMsg.Length);
}
private Byte[] formatKey() {
int len = key.Length;
String strKey = System.Text.Encoding.UTF8.GetString(key);
String fillKey = "";
String strFormatedKey = "";
Byte[] formatedKeyByte;
if (len < 16)
fillKey = new String('X',(16 - len));
strFormatedKey = String.Concat(strKey, fillKey);
formatedKeyByte = Encoding.ASCII.GetBytes(strFormatedKey);
return formatedKeyByte;
}
}
}
Menu.cs
using System;
namespace RijndaelAlgorithm {
public class Menu {
private CryptDecrypt r;
public Menu() {
r = new CryptDecrypt("123654");
}
public void showMenu() {
Console.WriteLine("the encrypted message is: " + r.encryptMsg("isjustatest"));
}
}
}
You seem to want to encrypt a message with your .NET application and want to get the same encrypted bytes as a particular online service that you mention in one of your comments.
Parameter
One parameter for an encryption is the initialization vector (IV). It should be random and used only once. So if two apps are correctly implemented (with different random IVs), the encrypted bytes are different.
This service returns a different result every time you press the key, even if you use the same input.
However, if you generally take the different encrypted results and decrypt them with the same key, you will get the original bytes back.
The next problem with testing with this specific service is, that they delivering always the same prefix base64 sequence 'U2FsdGVkX1'. This is not standard AES output (if you decode this base64 sequence you get 'Salted_P'). So it makes sense to use a different online service for tests.
So if two AES-256 encoding implementations are using the same parameters, we will get the same encoded result. We need for it:
Key (32 bytes, not 16 for AES-256)
IV (16 bytes)
Speaking of key length: As others mentioned in the comments, you should not simply add "X" or something similar, but use a standard cryptographic mechanism to derive a good key.
Convenient for tests are methods that convert hex strings to byte arrays and back, e.g. see StringToByteArray and ByteArrayToString methods in this cool answer:
https://stackoverflow.com/a/311179
Let's give it a try. If we take your message 'isjustatest' which has the hex string'69736a7573746174657374374', we need a 32-byte key for AES-256 and 16 bytes IV.
As others mentioned in the comments, you need to flush and close the stream (or better yet, use a 'using' statement).
Taking your code and change the key and iv assignment and output the encrypted message to the console:
rijAlg.Key = StringToByteArray("519C7C3402A943D8AF83746C1548E475319EBDA6A38046059F83B21709BD6A5B"); //32 bytes
rijAlg.IV = StringToByteArray("0D024CF947CE4C288880D0B34D29BFA5"); // 16 bytes
...
swEncrypt.Write(originalMsg);
swEncrypt.Flush();
swEncrypt.Close();
...
Console.WriteLine("encrypted bytes: '" + ByteArrayToString(encryptedMsg) + "'");
This results in the output of '419536f27da3406625b2d07f43833aab' in the debug console.
So now we can use an online service, e.g. https://cryptii.com/pipes/aes-encryption where we can enter input data, select the encryption algorithm, supply key and IV bytes and then we get the same result as in your program, see screenshot here:
As mentioned above, don't forget to use different random IVs when using it in a real application.

Converting code from PasswordDerivedBytes to Rfc2898DerivedBytes, unicode

I'm attempting to replace PasswordDerivedBytes with Rfc2898DerivedBytes but I'm having a problem with the latter when getting back a unicode encoded result.
Take this code for example:
[TestMethod]
public void DerivedBytesTest()
{
string encrypted = "y4Ijqo9Ga/mHlFbLHDdDUkYZlyu7CHF4PVXGLnb8by7FAVtCgPLhFSiA9Et6hDac";
string key = "{00B3403A-3C29-4f26-A9CC-14C411EA8547}";
string salt = "gT5M07XB9hHl3l1s";
string expected = "4552065703414505";
string decrypted;
decrypted = Decrypt(encrypted, key, salt, true);
Assert.IsTrue(decrypted == expected); // Works
decrypted = Decrypt(encrypted, key, salt, false);
Assert.IsTrue(decrypted == expected); // Doesn't work, get wrong unicode characters in 24 character string
}
private string Decrypt(string encrypted, string key, string salt, bool legacy = false)
{
UnicodeEncoding encoding = new UnicodeEncoding();
byte[] encryptedDataBytes = Convert.FromBase64String(encrypted);
byte[] saltBytes = encoding.GetBytes(salt);
RijndaelManaged encryption = new RijndaelManaged();
DeriveBytes secretKey;
if (legacy)
{
secretKey = new PasswordDeriveBytes(key, saltBytes) {IterationCount = 100};
encryption.Padding = PaddingMode.PKCS7;
}
else
{
secretKey = new Rfc2898DeriveBytes(key, saltBytes, 100);
encryption.Padding = PaddingMode.Zeros; // This is the only one that doesn't throw the "Padding is invalid and cannot be removed" exception, but gives me a non-ASCII result
}
ICryptoTransform decryptor = encryption.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
string decryptedText = "";
using (MemoryStream memoryStream = new MemoryStream(encryptedDataBytes))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
byte[] bytes = new byte[encryptedDataBytes.Length];
int decryptedCount = cryptoStream.Read(bytes, 0, bytes.Length);
decryptedText = encoding.GetString(bytes, 0, decryptedCount);
if (!legacy)
{
// Something more to do with result?
}
}
}
return decryptedText;
}
I wonder if anyone can advise where I'm going wrong?
PasswordDeriveBytes is a badly implemented extension of PBKDF1, while Rfc2898DeriveBytes is the implementation of PBKDF2. Both derive a key from a password, but they are two different algorithms and therefore they derive two different results. As they are using cryptographically secure hashes underneath, there is no way to convert one to another.
If you can spare a few bytes of storage you could still derive the key using PKBDF1 and then encrypt that key using the result of PBKDF2. If the output size is identical you could even use XOR encryption for that (a one-time-pad) but AES would of course also work. So then the decryption becomes: calculate PBKDF2 result, decrypt data key, use data key to decrypt ciphertext.
Otherwise you will have to decrypt and then re-encrypt the result.
If you want to compare the decryption result then compare the resulting bytes; do not first convert it into a string. Using authenticated encryption or a MAC is highly advised so that a authentication tag can be validated instead. Just ignoring padding exceptions by using Zero Padding is not the way to go. These padding errors occur because the key is wrong.
Generic notes:
PasswordDeriveBytes should not be used for any amount of bytes > 20 bytes as the Mickeysoft extension of PBKDF1 is horribly insecure, even repeating bytes in the output (!). If you do the same for PBKDF2 then any adversary will have to do half the work that you have to do so that's not a good idea either.
The iteration count in the question is very low, but as you seem to use a highly random UID instead of a password that should be OK.

C# Bouncy Castle does not decrypt, Exception: pad block corrupted

In my app on windows phone 8 I need to encrypt-decrypt data using DESede/CBC/PKCS5Padding with PBKDF2 key.
I found example how to encrypt using Bouncy Castle: http://www.go4expert.com/articles/bouncy-castle-net-implementation-triple-t24829/
And I was able to encrypt my data (text), but I can't decrypt my encrypted data using this code.
When I'm trying to call DoFinal() it throws exception "pad block corrupted".
Maybe I missed something in decrypting?
Maybe somebody knows alternative library (way) on windows phone 8 for encryption using DESede/CBC/PKCS5Padding with PBKDF2 key?
using Raksha.Crypto;
using Raksha.Crypto.Engines;
using Raksha.Crypto.Modes;
using Raksha.Crypto.Paddings;
using Raksha.Crypto.Parameters;
using System;
using System.Security.Cryptography;
using System.Text;
namespace MyNamespace
{
class EncryptDecrypt
{
Rfc2898DeriveBytes key;
BufferedBlockCipher cipherEncrypt;
BufferedBlockCipher cipherDecrypt;
private readonly int ITERACTIONCOUNT = 1000;
private readonly int KEY_LENGTH = 24;
public EncryptDecrypt(string passPhrase, string salt)
{
byte[] SALT = Encoding.UTF8.GetBytes(salt);
key = new Rfc2898DeriveBytes(passPhrase, SALT, ITERACTIONCOUNT);
DesEdeEngine desede = new DesEdeEngine();
cipherEncrypt = new PaddedBufferedBlockCipher(new CbcBlockCipher(desede));
cipherDecrypt = new PaddedBufferedBlockCipher(new CbcBlockCipher(desede));
DesEdeParameters p = new DesEdeParameters(key.GetBytes(KEY_LENGTH));
cipherEncrypt.Init(true, p);
cipherDecrypt.Init(false, p);
}
public byte[] Encrypt(byte[] dataToEncrypt)
{
try
{
byte[] outbytes = cipherEncrypt.DoFinal(dataToEncrypt);
return outbytes;
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine("Encrypt() Exception: " + ex.Message);
return new byte[] { 0 };
}
}
public byte[] Decrypt(byte[] dataToDecrypt)
{
try
{
byte[] result = cipherDecrypt.DoFinal(dataToDecrypt);
return result;
}
catch(CryptoException ex)
{
System.Diagnostics.Debug.WriteLine("Decrypt() Exception: " + ex.Message);
// ex.Message: pad block corrupted
return new byte[] { 0 };
}
}
}
I solved the problem!
The DesEdeEngine must be initialized with first parameter true.
DesEdeEngine desede = new DesEdeEngine();
desede.Init(true, key);
I don't know why but it's does't matter that I use the same object of DesEdeEngine in the cipher to decrypt.
In a nutshell the DesEdeEngine by default is initialized as decryptor, and instead of encrypt it's decrypt block of padding bytes. And when PaddedBufferedBlockCipher in DoFinal() call PadCount() where value of last byte must be > 0 and < 8 I was getting value like 48 or 123 or something like this and it's threw an exception "pad block corrupted".
Thanks to all who participated.
There are many things that can cause a "Bad Padding" error. Basically anything that causes the end of the last block not to match the expected padding will throw the error. Possible causes include: incorrect padding setting, incorrect key, corrupted cyphertext and others.
To try and diagnose the problem, set the decryption side to NoPadding. This will accept anything, and allow you to examine the output:
complete garbage: you probably have an error in the key or different mode settings.
first block garbage: you may have a key error or an IV error.
last block garbage: likely a corrupt end to the cyphertext file.
a correct decryption with some strange bytes after: the strange bytes are the padding.
If it really is just the padding, then set the decryption function to expect that sort of padding. Otherwise check that the key/IV/cyphertext is byte-for-byte the same for both encryption and decryption.
It is vital that you set a padding mode after diagnosis. NoPadding is insecure.
In the case of your code I cannot see where you set the PKCS5 padding. I assume the CBC mode is set internally in CbcBlockCipher(desede).

Categories