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);
}
Related
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×tamp=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×tamp=2022-07-06t11:10:43&expiration=2022-07-06t11:15:43"; // 69 chars-long
secret = "id=jsmith1×tamp=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×tamp=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×tamp=2022-07-06t11:10:43&expiration=2022-07-06t11:15:43";
// Will work:
//$secret = "id=jsmith×tamp=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.
I need to encrypt a URL. According the specs of the URL it should be (Rijndael) encoded using CBC encryption mode, using an IV of 0., PKCS7 padding and a key length of 128-bit.
The decryption of the URL is done in a .NET environment using the RijndaelManaged class. I encrypt using OpenSSL 1.0.2a (C++ unmanaged) and use the following code (from the internet):
// ctx holds the state of the encryption algorithm so that it doesn't
// reset back to its initial state while encrypting more than 1 block.
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
unsigned char key[] = {0x41, 0x41, 0x45, 0x43, 0x41, 0x77, 0x51, 0x46,
0x43, 0x67, 0x63, 0x49, 0x43, 0x5A, 0x6F, 0x4C };
unsigned char iv[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
assert(sizeof(key) == 16); // AES128 key size
assert(sizeof(iv) == 16); // IV is always the AES block size
// If data isn't a multiple of 16, the default behavior is to pad with
// n bytes of value n, where n is the number of padding bytes required
// to make data a multiple of the block size. This is PKCS7 padding.
// The output then will be a multiple of the block size.
std::string plain("someId=007&accountNo=119955244351&user=admin&");
std::vector<unsigned char> encrypted;
size_t max_output_len = plain.length() + 16 - (plain.length() % 16);
encrypted.resize(max_output_len);
// Enc is 1 to encrypt, 0 to decrypt, or -1 (see documentation).
EVP_CipherInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, iv, 1);
// EVP_CipherUpdate can encrypt all your data at once, or you can do
// small chunks at a time.
int actual_size = 0;
if( !EVP_CipherUpdate(&ctx,
&encrypted[0], &actual_size,
reinterpret_cast<unsigned char *>(&plain[0]), plain.size()))
{
EVP_CIPHER_CTX_cleanup(&ctx);
}
// EVP_CipherFinal_ex is what applies the padding. If your data is
// a multiple of the block size, you'll get an extra AES block filled
// with nothing but padding.
int final_size;
EVP_CipherFinal_ex(&ctx, &encrypted[actual_size], &final_size);
actual_size += final_size;
encrypted.resize(actual_size);
for( size_t index = 0; index < encrypted.size(); ++index )
{
std::cout << std::hex << std::setw(2) << std::setfill('0') <<
static_cast<unsigned int>(encrypted[index]);
}
std::cout << "\n";
EVP_CIPHER_CTX_cleanup(&ctx);
AESWrapper aesWrapper;
std::string encryptedbase64(aesWrapper.base64encode( &encrypted[0], encrypted.size()));
I've checked (obviously) the key, the iv and the algorithm aes-cbc-128 and afaik OpenSSL uses PKCS7 padding by default, but the result doesn't match!
Striking is that the padding doesn't seem to happen in EVP_CipherFinal_ex.The padding should consist of the required number of bytes to get the correct blocksize, filling each byte with that number. But it appears to be filled with random data (or maybe more encryption?)
Is there an issue with this code, that can explain why the encryption is not 'correct'?
Should I focus on the incorrect padding and how to debug in that case?
Any pointers?
Nevermind. I got it working. The C# application that decrypts the URL uses a SHA1 hash on the key. After I hashed my key before encrypting the URL it started working.
I am looking for a cross platform way to share public keys for ECDSA signing. I had a great thing going from a performance perspective with CngKey and the standard .NET crypto libraries, but then I couldn't figure out how a 33 (or 65) byte public key (using secp256r1/P256) was getting turned into 104 bytes by MS.. Ergo, I couldn't support cross platform signing and verifying..
I'm using BouncyCastle now, but holy handgranade is it SLOW!
So, looking for suggestions for the following requirements:
Cross platform/Languages (server is .NET, but this is served up via a JSON/Web.API interface)
JavaScript, Ruby, Python, C++ etc..
Not crazy as slow on the server
Not so painfully slow people can't use it on the client.
The client has to be able to sign the message, the server has to be able to validate the signature with a public key that was exchanged at registration to the service.
Anyways, Ideas would be awesome... Thanks
So I have figured out the format of a CngKey exported in ECCPublicKeyBlob and ECCPrivateKeyBlob. This should allow others to interop between other key formats and CngKey for Elliptcal Curve signing and such.
ECCPrivateKeyBlob is formatted (for P256) as follows
[KEY TYPE (4 bytes)][KEY LENGTH (4 bytes)][PUBLIC KEY (64 bytes)][PRIVATE KEY (32 Bytes)]
KEY TYPE in HEX is 45-43-53-32
KEY LENGTH in HEX is 20-00-00-00
PUBLIC KEY is the uncompressed format minus the leading byte (which is always 04 to signify an uncompressed key in other libraries)
ECCPublicKeyBlob is formatted (for P256) as follows
[KEY TYPE (4 bytes)][KEY LENGTH (4 bytes)][PUBLIC KEY (64 bytes)]
KEY TYPE in HEX is 45-43-53-31
KEY LENGTH in HEX is 20-00-00-00
PUBLIC KEY is the uncompressed format minus the leading byte (which is always 04 to signify an uncompressed key in other libraries)
So given a uncompressed Public key in Hex from another language, you can trim the first byte, add those 8 bytes to the front and import it using
CngKey.Import(key,CngKeyBlobFormat.EccPrivateBlob);
Note: The key blob format is documented by Microsoft.
The KEY TYPE and KEY LENGTH are defined in BCRYPT_ECCKEY_BLOB struct as:
{ ulong Magic; ulong cbKey; }
ECC public key memory format:
BCRYPT_ECCKEY_BLOB
BYTE X[cbKey] // Big-endian.
BYTE Y[cbKey] // Big-endian.
ECC private key memory format:
BCRYPT_ECCKEY_BLOB
BYTE X[cbKey] // Big-endian.
BYTE Y[cbKey] // Big-endian.
BYTE d[cbKey] // Big-endian.
The MAGIC values available in .NET are in Microsoft's official GitHub dotnet/corefx BCrypt/Interop.Blobs.
internal enum KeyBlobMagicNumber : int
{
BCRYPT_ECDH_PUBLIC_P256_MAGIC = 0x314B4345,
BCRYPT_ECDH_PRIVATE_P256_MAGIC = 0x324B4345,
BCRYPT_ECDH_PUBLIC_P384_MAGIC = 0x334B4345,
BCRYPT_ECDH_PRIVATE_P384_MAGIC = 0x344B4345,
BCRYPT_ECDH_PUBLIC_P521_MAGIC = 0x354B4345,
BCRYPT_ECDH_PRIVATE_P521_MAGIC = 0x364B4345,
BCRYPT_ECDSA_PUBLIC_P256_MAGIC = 0x31534345,
BCRYPT_ECDSA_PRIVATE_P256_MAGIC = 0x32534345,
BCRYPT_ECDSA_PUBLIC_P384_MAGIC = 0x33534345,
BCRYPT_ECDSA_PRIVATE_P384_MAGIC = 0x34534345
BCRYPT_ECDSA_PUBLIC_P521_MAGIC = 0x35534345,
BCRYPT_ECDSA_PRIVATE_P521_MAGIC = 0x36534345,
...
...
}
Thanks to you I was able to import a ECDSA_P256 public key from a certificate with this code:
private static CngKey ImportCngKeyFromCertificate(X509Certificate2 cert)
{
var keyType = new byte[] {0x45, 0x43, 0x53, 0x31};
var keyLength = new byte[] {0x20, 0x00, 0x00, 0x00};
var key = cert.PublicKey.EncodedKeyValue.RawData.Skip(1);
var keyImport = keyType.Concat(keyLength).Concat(key).ToArray();
var cngKey = CngKey.Import(keyImport, CngKeyBlobFormat.EccPublicBlob);
return cngKey;
}
The 65 byte keys (public key only) start with 0x04 which needs to be removed. Then the header you described is added.
then I was able to verify a signature like that:
var crypto = ECDsaCng(cngKey);
var verify = crypto.VerifyHash(hash, sig);
I just thought I would say thanks to both above posts as it helped me out tremendously. I had to verify a signature using RSA public key using the RSACng object. I was using the RSACryptoServiceProvider before, but that is not FIPS compliant, so I had some problems switching to RSACng. It also requires .NET 4.6. Here is how I got it to work using the above posters as an example:
// This structure is as the header for the CngKey
// all should be byte arrays in Big-Endian order
//typedef struct _BCRYPT_RSAKEY_BLOB {
// ULONG Magic;
// ULONG BitLength;
// ULONG cbPublicExp;
// ULONG cbModulus;
// ULONG cbPrime1; private key only
// ULONG cbPrime2; private key only
//} BCRYPT_RSAKEY_BLOB;
// This is the actual Key Data that is attached to the header
//BCRYPT_RSAKEY_BLOB
// PublicExponent[cbPublicExp]
// Modulus[cbModulus]
//first get the public key from the cert (modulus and exponent)
// not shown
byte[] publicExponent = <your public key exponent>; //Typically equal to from what I've found: {0x01, 0x00, 0x01}
byte[] btMod = <your public key modulus>; //for 128 bytes for 1024 bit key, and 256 bytes for 2048 keys
//BCRYPT_RSAPUBLIC_MAGIC = 0x31415352,
// flip to big-endian
byte[] Magic = new byte[] { 0x52, 0x53, 0x41, 0x31};
// for BitLendth: convert the length of the key's Modulus as a byte array into bits,
// so the size of the key, in bits should be btMod.Length * 8. Convert to a DWord, then flip for Big-Endian
// example 128 bytes = 1024 bits = 0x00000400 = {0x00, 0x00, 0x04, 0x00} = flipped {0x00, 0x04, 0x00, 0x00}
// example 256 bytes = 2048 bits = 0x00000800 = {0x00, 0x00, 0x08, 0x00} = flipped {0x00, 0x08, 0x00, 0x00}
string sHex = (btMod.Length * 8).ToString("X8");
byte[] BitLength = Util.ConvertHexStringToByteArray(sHex);
Array.Reverse(BitLength); //flip to Big-Endian
// same thing for exponent length (in bytes)
sHex = (publicExponent.Length).ToString("X8");
byte[] cbPublicExp = Util.ConvertHexStringToByteArray(sHex);
Array.Reverse(cbPublicExp);
// same thing for modulus length (in bytes)
sHex = (btMod.Length).ToString("X8");
byte[] cbModulus = Util.ConvertHexStringToByteArray(sHex);
Array.Reverse(cbModulus);
// add the 0 bytes for cbPrime1 and cbPrime2 (always zeros for public keys, these are used for private keys, but need to be zero here)
// just make one array with both 4 byte primes as zeros
byte[] cbPrimes = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
//combine all the parts together into the one big byte array in the order the structure
var keyImport = Magic.Concat(BitLength).Concat(cbPublicExp).Concat(cbModulus).Concat(cbPrimes).Concat(publicExponent).Concat(btMod).ToArray();
var cngKey = CngKey.Import(keyImport, CngKeyBlobFormat.GenericPublicBlob);
// pass the key to the class constructor
RSACng rsa = new RSACng(cngKey);
//verify: our randomly generated M (message) used to create the signature (not shown), the signature, enum for SHA256, padding
verified = rsa.VerifyData(M, signature, HashAlgorithmName.SHA256,RSASignaturePadding.Pkcs1);
Note: The sign byte for the modulus (0x00) can either be included in the modulus or not, so the length will be one bigger if it is included. CNGkey seems to handle it ok either way.
You convert EC key to BCRYPT_ECCKEY_BLOB by like this. We should ignore the first byte from EC key because it just represent compressed/uncompressed format.
BCRYPT_ECCKEY_BLOB eccBlobHeader;
PCHAR bycrtptKey;
eccBlobHeader.dwMagic = BCRYPT_ECDH_PUBLIC_P384_MAGIC;
eccBlobHeader.cbKey = 48;//size of EC key(without 1st byte)
memcpy(bycrtptKey, &eccBlobHeader, 8);//copying 8bytes header blob
memcpy(bycrtptKey+ 8,publicKeyFromOtherParty+1,publicKeyFromOtherPartySize- 1);
now use bycrtptKey for importing.
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);
}
I've got a project which stipulates the following encryption rules for a 24 byte block of data.
1) Cryptography should be done using full triple DES MAC algorithm as defined in 9797-1 as MAC
algorithm 3 with output transformation 3 without truncation and with DES in CBC mode as block
cipher with ICV set to zeros. Last 8 bytes of encrypted data constitute the value we need.
The program is saying the encryption done is wrong. Are there any other things I need to do to match the above spec?
The data is a 24 byte value and output of the encryption should be 8 bytes, I guess (as per the spec). I am getting the whole 24 bytes as output :(
I wrote the following code to achieve the said specification:
des.KeySize = 128;
des.Key = ParseHex(key);
des.Mode = CipherMode.CBC;
des.Padding = PaddingMode.None;
ICryptoTransform ic = des.CreateEncryptor();
CryptoOutput = ic.TransformFinalBlock(CryptoOutput, 0, 24);
I tried this also:
MACTripleDES des = new MACTripleDES(ParseHex(key));
byte[] CDCryptp = des.ComputeHash(CryptoOutput);
ISO 9797-1 MAC Algorithm 3 consists of using the first DES key to perform a CBC MAC and then only for the final block perform a full 3-DES operation.
Try this:
byte[] keybytes = ParseHex(key);
byte[] key1 = new byte[8];
Array.Copy(keybytes, 0, key1, 0, 8);
byte[] key2 = new byte[8];
Array.Copy(keybytes, 8, key2, 0, 8);
DES des1 = DES.Create();
des1.Key = key1;
des1.Mode = CipherMode.CBC;
des1.Padding = PaddingMode.None;
des1.IV = new byte[8];
DES des2 = DES.Create();
des2.Key = key2;
des2.Mode = CipherMode.CBC;
des2.Padding = PaddingMode.None;
des2.IV = new byte[8];
// MAC Algorithm 3
byte[] intermediate = des1.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);
// Output Transformation 3
byte[] intermediate2 = des2.CreateDecryptor().TransformFinalBlock(intermediate, intermediate.Length - 8, 8);
byte[] result = des1.CreateEncryptor().TransformFinalBlock(intermediate2, 0, 8);
For CBC-MAC mode you should encrypt the whole message in CBC mode with zero initialization vector (IV), and take only the last 8 bytes (for DES) of the output.
Also, since you need to use DES, it should have 64 bit key, not 128.
If you can quote the ISO (cannot find free copy), I can describe what you should do in more details.
The question is perhaps not as well worded as it ought to be, and looks a lot like homework. So I'll point you at some links, which you may not have seen yet, so you can learn.
Someone else is doing 3DES MAC values at TripleDES: Specified key is a known weak key for 'TripleDES' and cannot be used although I would not recommend altering the behavior of .NET like some of the answers there.
If all you need is to just use 3DES, check this out: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/b9239824-e8a1-4955-9193-d9f6993703f3/