Need PHP 8 version of C#/.NET encryption code - c#

An encryption C# code that has been in use for many years now needs to be converted to PHP 8.
I came close, and there's one remaining issue as described below:
For example, the secret below is longer than 71 characters and it is not encrypted correctly:
secret = "id=jsmith12&timestamp=2022-07-06t11:10:43&expiration=2022-07-06t11:15:43"; //71 chars-long
However, these secrets will be encrypted correctly, since they are less than 71 chars long:
secret = "id=jsmith&timestamp=2022-07-06t11:10:43&expiration=2022-07-06t11:15:43"; // 69 chars-long
secret = "id=jsmith1&timestamp=2022-07-06t11:10:43&expiration=2022-07-06t11:15:43"; // 70 chars-long
There is an online page where you can test if the generated token is correct: https://www.mybudgetpak.com/SSOTest/
You can evaluate the token by providing the generated token, the key, and the encryption method (Rijndael or Triple DES).
If the evaluation (decryption of the token) is successful, the test page will diplay the id, timestamp and expiration values
used in the secret.
C# Code:
The secret, a concatenated query string values, what needs to be encrypted:
string secret = "id=jsmith123&timestamp=2022-07-06t11:10:43&expiration=2022-07-06t11:15:43";
The key:
string key = "C000000000000000"; //16 character-long
ASCII encoded secret and key converted to byte array:
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] encodedSecret = encoding.GetBytes(secret);
byte[] encodedKey = encoding.GetBytes(key);
Option 1: Rijndael
// Call the generate token method:
string token = GenerateRijndaelSecureToken(encodedSecret, encodedKey);
private string GenerateRijndaelSecureToken(byte[] encodedSecret, byte[] encodedKey)
{
Rijndael rijndael = Rijndael.Create();
// the encodedKey must be a valid length so we pad it until it is (it checks // number of bits)
while (encodedKey.Length * 8 < rijndael.KeySize)
{
byte[] tmp = new byte[encodedKey.Length + 1];
encodedKey.CopyTo(tmp, 0);
tmp[tmp.Length - 1] = (byte)'\0';
encodedKey = tmp;
}
rijndael.Key = encodedKey;
rijndael.Mode = CipherMode.ECB;
rijndael.Padding = PaddingMode.Zeros;
ICryptoTransform ict = rijndael.CreateEncryptor();
byte[] result = ict.TransformFinalBlock(encodedSecret, 0, encodedSecret.Length);
// convert the encodedSecret to a Base64 string to return
return Convert.ToBase64String(result);
}
Option 2: Triple DES
// Call the generate token method:
string token = GenerateSecureTripleDesToken(encodedSecret, encodedKey);
private string generateSecureTripleDesToken(byte[] encodedSecret, byte[] encodedKey)
{
// Generate the secure token (this implementation uses 3DES)
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
// the encodedKey must be a valid length so we pad it until it is (it checks // number of bits)
while (encodedKey.Length * 8 < tdes.KeySize)
{
byte[] tmp = new byte[encodedKey.Length + 1];
encodedKey.CopyTo(tmp, 0);
tmp[tmp.Length - 1] = (byte) '\0';
encodedKey = tmp;
}
tdes.Key = encodedKey;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.Zeros;
ICryptoTransform ict = tdes.CreateEncryptor();
byte[] result = ict.TransformFinalBlock(encodedSecret, 0, encodedSecret.Length);
// convert the encodedSecret to a Base64 string to return
return Convert.ToBase64String(result);
}
PHP 8 code:
public $cipher_method = "AES-256-ECB";
// Will not work:
//$secret = "id=jsmith12&timestamp=2022-07-06t11:10:43&expiration=2022-07-06t11:15:43";
// Will work:
//$secret = "id=jsmith&timestamp=2022-07-06t11:10:43&expiration=2022-07-06t11:15:43";
$key = "C000000000000000";
$token = openssl_encrypt($secret, $cipher_method, $key);

There are two things to be aware of:
The C# code pads the key with 0x00 values to the required length, i.e. 256 bits for AES-256 and 192 bits for 3DES. Since PHP/OpenSSL automatically pads keys that are too short with 0x00 values, this does not need to be implemented explicitly in the PHP code (although it would be more transparent).
The C# code uses Zero padding. PHP/OpenSSL on the other hand applies PKCS#7 padding. Since PHP/OpenSSL does not support Zero padding, the default PKCS#7 padding must be disabled with OPENSSL_ZERO_PADDING (note: this does not enable Zero padding, the name of the flag is poorly chosen) and Zero padding must be explicitly implemented, e.g. with:
function zeropad($data, $bs) {
$length = ($bs - strlen($data) % $bs) % $bs;
return $data . str_repeat("\0", $length);
}
Here $bs is the block size (16 bytes for AES and 8 bytes for DES/3DES).
Further changes are not necessary! A possible implementation is:
$cipher_method = "aes-256-ecb"; // for AES (32 bytes key)
//$cipher_method = "des-ede3"; // for 3DES (24 bytes key)
// Zero pad plaintext (explicitly)
$bs = 16; // for AES
//$bs = 8; // for 3DES
$secret = zeropad($secret, $bs);
// Zero pad key (implicitly)
$key = "C000000000000000";
$token = openssl_encrypt($secret, $cipher_method, $key, OPENSSL_ZERO_PADDING); // disable PKCS#7 default padding, Base64 encode (implicitly)
print($token . PHP_EOL);
The ciphertexts generated in this way can be decrypted using the linked website (regardless of their length).
The wrong padding causes decryption to fail on the web site (at least to not succeed reliably). However, the logic is not correct that decryption fails only if the plaintext is larger than 71 bytes (even if only the range between 65 and 79 bytes is considered). For example, decryption fails also with 66 bytes. The page source provides a bit more information than the GUI:
Could not read \u0027expiration\u0027 as a date: 2022-07-06t11:15:43\u000e\u000e\u000e\u000e\u000e\u000e\u000e\u000e\u000e\u000e\u000e\u000e\u000e\u000e
The problem is (as expected) the PKCS#7 padding bytes at the end: 14 0x0e values for 66 bytes.
Why decryption works for some padding bytes and not for others can only be reliably answered if the decryption logic of the web site were known. In the end, however, the exact reason doesn't matter.
Note that the applied key expansion is insecure. Also, ECB is insecure, 3DES is outdated, and Zero padding is unreliable.

Related

AES Encryption with EasyCrypto C# and Decryption in C++ using Crypto++

I have encrypted a string using EasyCrypto in C# using the following code
Encryption C#:
/*
EasyCrypto encrypted key format from CryptoContainer.cs file from the EasyCrypto source on GitHub.
* Format:
* 04 bytes 00 - MagicNumber
* 02 bytes 04 - DataVersionNumber
* 02 bytes 06 - MinCompatibleDataVersionNumber
* 16 bytes 08 - IV
* 32 bytes 24 - Salt
* 19 bytes 56 - Key check value
* 48 bytes 75 - MAC
* 04 bytes 123 - Additional header data length
* xx bytes 127 - Additional data
* ----- end of header ----- (sum: 127)
* xx bytes - additional header data (0 for version 1)
* xx bytes - data
*/
AesEncryption.EncryptWithPassword("data to encrypt", "password string");
/*
Method Description:
Encrypts string and returns string. Salt and IV will be embedded to encrypted string. Can later be decrypted with
EasyCrypto.AesEncryption.DecryptWithPassword(System.String,System.String,EasyCrypto.ReportAndCancellationToken)
IV and salt are generated by EasyCrypto.CryptoRandom which is using System.Security.Cryptography.Rfc2898DeriveBytes.
IV size is 16 bytes (128 bits) and key size will be 32 bytes (256 bits).
/*
I am trying to decrypt in C++ using Crypto++, using the following code. I am just getting the error "ciphertext length is not a multiple of block size", what is the missing part in the code? any help would be highly appreciable.
Decryption C++:
string Decrypt() {
// getting CryptoPP::byte array from passowrd
string destination;
CryptoPP::StringSource ss(<hex of password string>, true, new CryptoPP::HexDecoder(new CryptoPP::StringSink(destination)));
CryptoPP::byte* keyByteArray = (CryptoPP::byte*)destination.data();
// getting CryptoPP::byte array from encoded data
string pkDst;
CryptoPP::StringSource ss2(<hex of encoded data>, true, new CryptoPP::HexDecoder(new CryptoPP::StringSink(pkDst)));
CryptoPP::byte* pkByteArray = (CryptoPP::byte*)pkDst.data();
// getting initialization vector from encoded data
CryptoPP::byte iv[16];
for (int i = 8; i < 24; i++) {
iv[i] = pkByteArray[i];
}
string result = CBCMode_Decrypt(keyByteArray, 32, iv);
return result;
}
string CBCMode_Decrypt(CryptoPP::byte key[], int keySize, CryptoPP::byte iv[]) {
string recovered = "";
//Decryption
try
{
CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption d;
d.SetKeyWithIV(key, keySize, iv);
// The StreamTransformationFilter removes
// padding as required.
CryptoPP::StringSource s("encoded string", true, new CryptoPP::StreamTransformationFilter(d, new CryptoPP::StringSink(recovered))); // StringSource
}
catch (const CryptoPP::Exception& e)
{
cerr << e.what() << endl;
exit(1);
}
return recovered;
}
In the Crypto++ code, the following steps must be performed for decryption:
Base64 decoding of the EasyCrypto data
Separating IV, salt and ciphertext (using the information from the CryptoContainer.cs file)
Deriving the 32 bytes key via PBKDF2 using salt and password (digest: SHA-1, iteration count: 25000)
Decryption with AES-256 in CBC mode and PKCS#7 padding (using key and IV)
A possible Crypto++ implementation is:
#include "aes.h"
#include "modes.h"
#include "pwdbased.h"
#include "sha.h"
#include "base64.h"
using namespace CryptoPP;
using namespace std;
...
// Base64 decode data from EasyCrypto
string encoded = "bqCrDAQABABtXsh2DxqYdpZc6M6+kGALOsKUHzxoMR6WAVg5Qtj3zWbr4MiEBdqt9nPIiIZAynFAZmweHQPa/PhEItR6M8Jg1bHAYeQ8Cm5eUlKNzPXFNfuUw0+qtds29S0L4wAWY0xfuiBJTUeTJuSLWqoirm/rHGOWAAAAAKtBivUDvxta1d0QXE6J9x5VdSpAw2LIlXARKzmz+JRDtJcaj4KmGmXW/1GjZlMiUA==";
string decoded;
StringSource ssB64(
encoded,
true,
new Base64Decoder(
new StringSink(decoded)
)
);
// Separate IV, salt and ciphertext
string ivStr = decoded.substr(8, 16);
string saltStr = decoded.substr(24, 32);
string ciphertextStr = decoded.substr(127);
// Derive 32 bytes key using PBKDF2
char password[] = "my passphrase";
unsigned int iterations = 25000;
byte key[32];
size_t keyLen = sizeof(key);
PKCS5_PBKDF2_HMAC<SHA1> pbkdf;
pbkdf.DeriveKey(key, keyLen, 0, (byte*)password, sizeof(password), (byte*)saltStr.c_str(), saltStr.length(), iterations, 0.0f);
// Decrypt with AES-256, CBC, PKCS#7 padding
string decrypted;
CBC_Mode<AES>::Decryption decryption(key, keyLen, (byte*)ivStr.c_str());
StringSource ssDec(
ciphertextStr,
true,
new StreamTransformationFilter(
decryption,
new StringSink(decrypted),
BlockPaddingSchemeDef::BlockPaddingScheme::PKCS_PADDING
)
);
// Output
cout << "Decrypted: " << decrypted << "\n";
with the output:
Decrypted: The quick brown fox jumps over the lazy dog
The ciphertext was generated with EasyCrypto:
AesEncryption.EncryptWithPassword("The quick brown fox jumps over the lazy dog", "my passphrase");
The previous section focused on decryption. Note, however, that for security reasons, authentication is required before decryption and decryption may only be performed on successfully authenticated data.
For authentication also the MAC must be determined in addition to IV, salt and ciphertext. EasyCrypto applies an HMAC-SHA-384 as MAC. Only the ciphertext is used to determine the MAC, and the key for authentication is the same as the key for encryption.
For authentication, the calculated and the sent MAC must be compared. If both are the same, the authentication is successful (and the decryption can be performed).
A possible Crypto++ implementation for the authentication is:
// Get the sent MAC
string macSentStr = decoded.substr(75, 48);
// Calculate the MAC using ciphertext and encryption key
string macCalcStr;
HMAC<SHA384> hmac(key, keyLen);
StringSource ssMac(
ciphertextStr,
true,
new HashFilter(hmac,
new StringSink(macCalcStr)
)
);
// Compare both MACs
cout << (!macSentStr.compare(macCalcStr) ? "Authentication successful" : "Authentication failed") << endl; // compare returns 0 if both strings match
which successfully authenticates the sample data.

AES 128 bit with ECB ciphermode algorithm decrypts correctly with an invalid key?

Hi i am learning Encryption / Decryption part. I have created two methods for Encryption / Decryption using AES 128 bit with ECB cipher mode and PKCS7 padding.
Below is the code.
public class EncClass
{
public string Encrypt(string text)
{
byte[] src = Encoding.UTF8.GetBytes(text);
byte[] key = Encoding.ASCII.GetBytes("contactcentre");
RijndaelManaged aes = new RijndaelManaged();
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
aes.KeySize = 128;
using (ICryptoTransform encrypt = aes.CreateEncryptor(key, null))
{
byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
encrypt.Dispose();
return Convert.ToBase64String(dest);
}
}
public string Decrypt(string text)
{
byte[] src = Convert.FromBase64String(text);
RijndaelManaged aes = new RijndaelManaged();
byte[] key = Encoding.ASCII.GetBytes("contactcentrT");
aes.KeySize = 128;
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.ECB;
using (ICryptoTransform decrypt = aes.CreateDecryptor(key, null))
{
byte[] dest = decrypt.TransformFinalBlock(src, 0, src.Length);
decrypt.Dispose();
return Encoding.UTF8.GetString(dest);
}
}
}
Notice that in Encryption i have passed contactcentre key and in decryption I have passed contactcentrT. It is doing proper encryption and decryption in that case.
var encString = encClass.Encrypt(#"manoj");
var decString = encClass.Decrypt(encString);
Though my both keys are not matching, still it is working properly. Just wanted to know how this could happen?
You are passing invalid key to aes.CreateEncryptor (and CreateDecryptor). Valid key sizes for AES are 128, 192 and 256, and your key is 13*8=104 bits. If you try to assign it to aes.Key - that will throw exception. However, aes.CreateEncryptor has a bug and it does not correctly validate key size if key size is less than block size (less than 128 bits), despite stating explicitly in documentation that "The key size must be 128, 192, or 256 bits". This bug is fixed in .NET Core by the way (at least in version 2) where it correctly throws exception for your code.
So, since you are passing invalid key and CreateEncryptor by mistake allowed it - you are not really encrypting with AES and anything can happen. For example if you pass key of 1 byte (or 2, or 7) - index out of range exception will be thrown. My assumption (by looking at source code) is algorithm implementation assumes key size in bytes is divisable by 4, and uses those 4-byte blocks. First 12 characters of your key are the same, and the rest (be it 1,2 or 3 characters) are not used, because number of 4-byte blocks is calculated as keySize / 4 (and 13 / 4 = 3).
Anyway, any assumptions of why this happens does not matter much, because algorithm is executed with invalid input and any results produced by doing that are irrelevant.
Given that info - never pass key directly to aes.CreateEncryptor but assign it to aes.Key first and then pass that (aes.CreateEncryptor(aes.Key, iv))

Generating PBKDF2 keys in C# and NodeJS

I'm trying to encrypt a byte array in C# using AES192 and a PBKDF2 password/salt based key and decrypt the same data in NodeJS. However my key generation produces different results in both NodeJS and C#.
The C# code is as follows:
private void getKeyAndIVFromPasswordAndSalt(string password, byte[] salt, SymmetricAlgorithm symmetricAlgorithm, ref byte[] key, ref byte[] iv)
{
Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt);
key = rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.KeySize / 8);
iv = rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.BlockSize / 8);
}
private byte[] encrypt(byte[] unencryptedBytes, string password, int keySize)
{
RijndaelManaged aesEncryption = new RijndaelManaged();
aesEncryption.KeySize = keySize;
aesEncryption.BlockSize = 128;
byte[] key = new byte[keySize];
byte[] iv = new byte[128];
getKeyAndIVFromPasswordAndSalt(password, Encoding.ASCII.GetBytes("$391Ge3%£2gfR"), aesEncryption, ref key, ref iv);
aesEncryption.Key = key;
aesEncryption.IV = iv;
Console.WriteLine("iv: {0}", Convert.ToBase64String(aesEncryption.IV));
Console.WriteLine("key: {0}", Convert.ToBase64String(aesEncryption.Key));
ICryptoTransform crypto = aesEncryption.CreateEncryptor();
// The result of the encryption and decryption
return crypto.TransformFinalBlock(unencryptedBytes, 0, unencryptedBytes.Length);
}
The NodeJS code reads like this:
crypto.pbkdf2("Test", "$391Ge3%£2gfR", 1000, 192/8, (err, key) => {
var binkey = new Buffer(key, 'ascii');
var biniv = new Buffer("R6taODpFa1/A7WhTZVszvA==", 'base64');
var decipher = crypto.createDecipheriv('aes192', binkey, biniv);
console.log("KEY: " + binkey.toString("base64"));
var decodedLIL = decipher.update(decryptedBuffer);
console.log(decodedLIL);
return;
});
The IV is hardcoded as I can't figure out how to calculate that using pbkdf2. I've looked through the nodeJS docs for more help but I'm at a loss as to what's going on here.
Any assistance would be greatly appreciated.
One of the issues I see is the encoding of the pound sign (£). crypto.pbkdf2 encodes the password and salt to a binary array by default, where each character is truncated to the lowest 8 bits (meaning the pound sign becomes the byte 0xA3).
However, your C# code converts the salt to ASCII, where each character is truncated to the lowest 7 bits (meaning the pound sign becomes the byte 0x23). Also it uses the Rfc2898DeriveBytes constructor that takes a String for the password. Unfortunately, the documentation doesn't say what encoding is used to convert the string to bytes. Fortunately, Rfc2898DeriveBytes does have another constructor that takes a byte array for the password and also takes an iteration count parameter, here 1000.
Accordingly, you should convert the password and salt strings to byte arrays by truncating each character to 8 bits, just like Node.js does by default. Here is an example:
var bytes=new byte[password.Length];
for(var i=0;i<bytes.Length;i++){
bytes[i]=(byte)(password[i]&0xFF);
}

Encrypting and Decrypting a 19-digits long BigInteger

How can I take a maximum 19-digits long BigInteger and encrypt it with the following rules:
The result must be based on digits and lower-case English letters only.
All outputs must have the same length to any input. The length must be between 11 to 16 characters, depending on your method, but should be consistent for all possible inputs.
No easy patterns. For example, if you encrypt 000...1 and 000...2 the results should look completely different.
No collisions at all
Should be able to decrypt back to the original BigInteger.
Things that I have tried
Take the original number, XOR it by some key, multiply it by a factor and convert it to a base 36 string. The purpose of the factor is to expand the range so there won't be too much 0 padding. The factor must be between 1 to 36^16/10^19. The problem with this method is that a) it's not 'secure' enough, and b) close numbers have very similar results.
This answer. However, the result was often too short or too long, and the factor method used before didn't work here.
19 digits is slightly less than 64 bits, so you can simply use a 8 byte block cipher like TDEA in ECB mode to encrypt the BigInteger values. First retrieve a default 64 bit encoding of the BigInteger, then encrypt with the secret key, and finally base 36 encode it. The result will be a few characters less than 16 characters, but you can always pad with any value.
Note that if you encrypt the same value twice that you will get the same result, so in that respect the ciphertext does leak some information about the plain text.
The technique you want is format perserving encryption. This will allow you to encrypt a 19 digit number as another 19 digit number.
Unfortunately, the efficient version of this technique is somewhat difficult to implement and in fact can be done very insecurely if you pick the wrong paramaters. There are libraries for it.
This one is open source. It is in C++ unfortunately and its not clear if it runs on windows. Voltage has a library as well, though it presumably costs money and I'm not sure what languages they support.
Here is a piece of code that seems to do it, provided you can convert the BigInteger into an ulong (9999999999999999999 is in fact an ulong). The result is always a fixed 16 characters string (hexadecimal).
byte[] key = // put your 16-bytes private key here
byte[] iv = Guid.NewGuid().ToByteArray(); // or anything that varies and you can carry
string s = EncryptUInt64(ul, key, iv); // encode
ulong dul = DecryptUInt64(s, key, iv).Value; // decode if possible
public static string EncryptUInt64(ulong ul, byte[] key, byte[] iv)
{
using (MemoryStream output = new MemoryStream())
using (var algo = TripleDES.Create())
{
algo.Padding = PaddingMode.None;
using (CryptoStream stream = new CryptoStream(output, algo.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
byte[] ulb = BitConverter.GetBytes(ul);
stream.Write(ulb, 0, ulb.Length);
}
return BitConverter.ToUInt64(output.ToArray(), 0).ToString("x16");
}
}
public static ulong? DecryptUInt64(string text, byte[] key, byte[] iv)
{
if (text == null)
return null;
ulong ul;
if (!ulong.TryParse(text, NumberStyles.HexNumber, null, out ul))
return null;
using (MemoryStream input = new MemoryStream(BitConverter.GetBytes(ul)))
using (var algo = TripleDES.Create())
{
algo.Padding = PaddingMode.None;
using (CryptoStream stream = new CryptoStream(input, algo.CreateDecryptor(key, iv), CryptoStreamMode.Read))
{
byte[] olb = new byte[8];
try
{
stream.Read(olb, 0, olb.Length);
}
catch
{
return null;
}
return BitConverter.ToUInt64(olb, 0);
}
}
}

Two-key triple DES encryption solution needed

Is this possible in C#? How would I accomplish this?
Two-key triple DES is where we encrypt with K1, then decrypt with K2 and finally encrypt again with K1. The keyspace is thus 2 x 56 = 112 bits.
For example, with K1=0x0123456789ABCDEF and K2=0xFEDCBA9876543210 you would set the triple DES key to be 0x0123456789ABCDEFFEDCBA98765432100123456789ABCDEF.
0123456789ABCDEF FEDCBA9876543210 0123456789ABCDEF
|<------K1------>|<------K2------>|<------K3------>|
It accepts A9993E364706816A and the 2 keys that it must use is K1 = 0123456789ABCDEF and K2 = FEDCBA9876543210. The end result must be: 6E5271A3F3F5C418 which I am not getting.
UPDATE:
I am trying to create the concatenated key that I need to use. The 2 keys used above is converted to a byte array and seems to have a length of 16 each. And when the 2 are concatenated then the length is 32. Then my code bombs out. The key has to have a length of 16 or 24. What do I need to do in this case?
UTF8Encoding characterEncoding = new UTF8Encoding();
byte[] accessKey1ByteArray = characterEncoding.GetBytes(accessKey1);
byte[] accessKey2ByteArray = characterEncoding.GetBytes(accessKey2);
byte[] accessKeysArray = accessKey1ByteArray.Concat(accessKey2ByteArray).ToArray();
Here is where I try to set my values:
public byte[] ComputeTripleDesEncryption(byte[] plainText, byte[] key)
{
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.Key = key;
des.GenerateIV();
des.Mode = CipherMode.ECB;
des.Padding = PaddingMode.None;
ICryptoTransform ic = des.CreateEncryptor();
byte[] enc = ic.TransformFinalBlock(plainText, 0, plainText.Length);
return enc;
}
UPDATE 2
Do I need to set the size? The byte array key that I am sending through is K1 + K2 + K1.
The text that I am sending through, do I need convert this to bytes like what you recommended, or can the following also do the trick?
UTF8Encoding characterEncoding = new UTF8Encoding();
byte[] block1ByteArray = characterEncoding.GetBytes(block1);
The value of block1 is: A9993E364706816A.
How I got A9993E364706816A was from my SHA-1 hashed result. The first 16 characters of this hashed result of my string that I want to encode.
This sounds like you just want to set a 128 bit key for the triple des key.
I believe in this case if you provide a 128 bit key it splits it into two 64 bit keys and uses the first as K1 and K3 and the second as K2 which is exactly what you want.
Unfortunately I can't find a source to quote on this but I did a lot of reading on the subject recently when implementing some crypto stuff myself and finding out about key lengths and this is what I discovered.
If you have K1 and K2 as byte arrays already then you should be able to just use a nice little linq extension method and do:
SymmetricAlgorithm cryptoService = new TripleDESCryptoServiceProvider();
byte[] myKey = K1.Concat(K2).ToArray();
cryptoService.Key = mKey;
That will then do as you want.
In response to your updated part of the question the two keys you have are hexdecimal representations of a sequence of bytes. 0x0123456789ABCDEF is 16 characters of hexdecimal but this is equivalent to 8 bytes of information since it is 4 bits in each character - two making up a byte.
To convert that string to a byte array the following function can be used:
public static byte[] StringToByteArray(String hex)
{
if (hex.Substring(0,2)=="0x")
hex = hex.Substring(2);
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;
}
(From How do you convert Byte Array to Hexadecimal String, and vice versa?)
This will then be used like this:
string K1="0x0123456789ABCDEF";
string K2="0xFEDCBA9876543210";
byte[] key = StringToByteArray(K1).Concat(StringToByteArray(K2)).ToArray();
When implementing TDES you will need to agree a key, Block Cipher mode, Padding method and in most Block modes you will need an initialisation Vector. You'll possibly also want to use a Message Authentication Code.
To get an initialisation vector you'll want to do something like:
cryptoService.GenerateIV();
byte[] iv = cryptoService.IV;
I strongly advise reading pages on encryption to understand better what the various things you are doing actually are rather than just writing the code. It will make you more confident in your security and make you sound more confident while dealing with others. I've taken the liberty of including some links, most of which can be found by just googling.
Useful links:
http://en.wikipedia.org/wiki/Initialization_vector - all about initialisation vectors
http://en.wikipedia.org/wiki/Triple_DES - on the TDES algorithm
http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation - How consecutive blocks of data interact with each other.
http://en.wikipedia.org/wiki/Padding_%28cryptography%29 - Not massively important except there are different ways of padding and both sides need to be using the same one (of course).
http://chargen.matasano.com/chargen/2009/7/22/if-youre-typing-the-letters-a-e-s-into-your-code-youre-doing.html - An excellent and amusing commentary on the use of encryption and where there are weaknesses and what encryption can and cannot do.
http://en.wikipedia.org/wiki/Message_authentication_code - How to confirm that your message hasn't been tampered with
To encrypt/decrypt data with the TripleDES algorithm, you can use the TripleDESCryptoServiceProvider Class. The algorithm supports key lengths from 128 bits to 192 bits in increments of 64 bits.
If you have two 64-bit keys
byte[] k1 = new byte[] { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };
byte[] k2 = new byte[] { 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10 };
and want to concatenate k1, k2 and k1 again to a 192-bit key, you can do this as follows:
byte[] key = new byte[K1.Length + K2.Length + K1.Length];
Buffer.BlockCopy(k1, 0, result, 0, 8);
Buffer.BlockCopy(k2, 0, result, 8, 8);
Buffer.BlockCopy(k1, 0, result, 16, 8);
Note that, in addition to the key, you also need an initialization vector:
byte[] iv = // ...
Example:
byte[] data = new byte[] { 0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A };
using (var csp = new TripleDESCryptoServiceProvider())
using (var enc = csp.CreateEncryptor(key, iv))
using (var stream = new MemoryStream())
using (var crypto = new CryptoStream(stream, enc, CryptoStreamMode.Write))
{
crypto.Write(data, 0, data.Length);
}

Categories