openssl returns Bad Magic Number [duplicate] - c#

This question already has an answer here:
C# version of OpenSSL EVP_BytesToKey method?
(1 answer)
Closed 6 years ago.
In my Linux machine i have a binary AES encrypted file:
head -c 100 Leela_Turanga.plr
�|�XѨ��>��c��N�Ώڤ�LW�M��t�p5=c.4���ᑸ�#Owl����M�d��>�ٷa�L�r|��ć�ڐ,��:����#�����\
Also i know that the file has been encryped using the password:
h3y_gUyZ
I am able to decrypt this file using .NET's RijndaelManaged class in the following routine:
public static bool decryptFile(string inputFile, string outputFile)
{
string s = "h3y_gUyZ";
UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
byte[] bytes = unicodeEncoding.GetBytes(s);
FileStream fileStream = new FileStream(inputFile, FileMode.Open);
RijndaelManaged rijndaelManaged = new RijndaelManaged();
CryptoStream cryptoStream = new CryptoStream(fileStream, rijndaelManaged.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
FileStream fileStream2 = new FileStream(outputFile, FileMode.Create);
try
{
int num;
while ((num = cryptoStream.ReadByte()) != -1)
{
fileStream2.WriteByte((byte)num);
}
fileStream2.Close();
cryptoStream.Close();
fileStream.Close();
}
catch
{
fileStream2.Close();
fileStream.Close();
File.Delete(outputFile);
return true;
}
return false;
}
Since im on Linux I embedded this code in a c# program which i run with mono, after i compiled it with mcs.
mcs *.cs -out:mybinary.exe
mono mybinary.exe d Leela_Turanga.plr outputfile.dat
Where the d parameter executes the aforementioned function, Leela_Turanga.plr is the file to decrypt and outputfile.dat is the resulting decryped file.
This works fine: I can decrypt the file correctly, and i am able to say this because human readable text appears in the decrypted file.
Now i want to decrypt the same file with openssl.
First of all i need to get the algorithm parameters, and since the code above works, I modified it to give me these informations:
Key Size
AES operation mode (cbc, ecb, pcbc, cfb...)
Padding (have no idea what that is)
by adding some code:
public static bool decryptFile(string inputFile, string outputFile)
{
string s = "h3y_gUyZ";
UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
byte[] bytes = unicodeEncoding.GetBytes(s);
FileStream fileStream = new FileStream(inputFile, FileMode.Open);
RijndaelManaged rijndaelManaged = new RijndaelManaged();
CryptoStream cryptoStream = new CryptoStream(fileStream, rijndaelManaged.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
FileStream fileStream2 = new FileStream(outputFile, FileMode.Create);
//=======DEBUG INFO=======
//PRINT ALGORITHM SETTINGS
Console.WriteLine(rijndaelManaged.Mode); //what AES mode are we using?
Console.WriteLine(rijndaelManaged.KeySize); //what is the keysize?
Console.WriteLine(rijndaelManaged.Padding); //what is the padding?
//========================
try
{
int num;
while ((num = cryptoStream.ReadByte()) != -1)
{
fileStream2.WriteByte((byte)num);
}
fileStream2.Close();
cryptoStream.Close();
fileStream.Close();
}
catch
{
fileStream2.Close();
fileStream.Close();
File.Delete(outputFile);
return true;
}
return false;
}
What it comes out is that RijndaelManaged is working in CBC mode, with a 256 bit key and PKCS7 Padding (again no idea if that is important).
Now i can try using openssl to decrypt:
openssl enc -aes-256-cbc -d -in Leela_Turanga.plr -out out.bin
Then the password prompt appears, I enter the pass, and a "bad magic number" error is returned"
enter aes-256-cbc decryption password:
bad magic number
And i get no decrypted file.
Why does openssl say that? I have searched on the internet but I haven't found my answer.
Also:
Since in c# strings are encoded in UTF-16 (hence 16 bits in a char), and the key is "h3y_gUyZ" which are 8 chars, shouldn't the key be 16 x 8 = 128 bits wide? instead of the 256 rijndaelManaged.KeySize returns.

Why does openssl say that?
OpenSSL uses it's own key derivation routine called EVP_BytesToKey, which takes a salt. This salt is prefixed with a 8 byte magic: Salted__ in ASCII encoding. Passwords should not be directly used as keys, so OpenSSL converts them to keys first.
You can instead provide a key using -K and then the hexadecimal representation of your string (read on for the encoding). You will also need to provide the IV (in your case the same bytes).
Since in C# strings are encoded in UTF-16 (hence 16 bits in a char), and the key is "h3y_gUyZ" which are 8 chars, shouldn't the key be 16 x 8 = 128 bits wide instead of the 256 rijndaelManaged.KeySize returns?
Yes, probably you asked the Rijndael class for the key size before initializing it with the key. And note that .NET uses UTF-16LE (little-endian) as the whole ecosystem is in (stupid) little-endian.
PKCS#7 is a standard that contains a padding scheme. It is both used by .NET and OpenSSL, so that's fine. It is required as ECB and CBC mode require the input size of the cipher is N times the block size of the cipher. So PKCS#7 adds 1 to 16 bytes (the block size of AES) valued \x01 to \x10. Unpadding removes these.

Related

AES-256-CBC in .NET Core (C#)

I am searching for C# Code to reproduce the following openssl command.
openssl enc -d -aes-256-cbc -in my_encrypted_file.csv.enc -out my_decrypted_file.csv -pass file:key.bin
Additional information:
The encrypted file in present as byte[]
The key.bin is a byte[] with length of 256 (the key is obtained by a more simple decryption of yet another file, which i managed to realize in C#).
I have been trying out various examples found by searching the web.
The problem is, that all of these examples require an IV (initialization vector). Unfortunately, I don't have an IV and no one on the team knows what this is or how it could be defined.
The openssl command does not seem to need one, so I am a bit confused about this.
Currently, the code, I am trying with, looks as follows:
public static string DecryptAesCbc(byte[] cipheredData, byte[] key)
{
string decrypted;
System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();
aes.KeySize = 256;
aes.Key = key;
byte[] iv = new byte[aes.BlockSize / 8];
aes.IV = iv;
aes.Mode = CipherMode.CBC;
ICryptoTransform decipher = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream(cipheredData))
{
using (CryptoStream cs = new CryptoStream(ms, decipher, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
decrypted = sr.ReadToEnd();
}
}
return decrypted;
}
}
The code fails saying that my byte[256] key has the wrong length for this kind of algorithm.
Thanks for any help with this!
Cheers, Mike
The posted OpenSSL statement uses the -pass file: option and thus a passphrase (which is read from a file), see openssl enc. This causes the encryption process to first generate a random 8 bytes salt and then, together with the passphrase, derive a 32 bytes key and 16 bytes IV using the (not very secure) proprietary OpenSSL function EVP_BytesToKey. This function uses several parameters, e.g. a digest and an iteration count. The default digest for key derivation is MD5 and the iteration count is 1. Note that OpenSSL version 1.1.0 and later uses SHA256 as default digest, i.e. depending on the OpenSSL version used to generate the ciphertext, the appropriate digest must be used for decryption. Preceding the ciphertext is a block whose first 8 bytes is the ASCII encoding of Salted__, followed by the 8 bytes salt.
Therefore, the decryption must first determine the salt. Based on the salt, together with the passphrase, key and IV must be derived and then the rest of the encrypted data can be decrypted. Thus, first of all an implementation of EVP_BytesToKey in C# is required, e.g. here. Then a possible implementation could be (using MD5 as digest):
public static string DecryptAesCbc(byte[] cipheredData, string passphrase)
{
string decrypted = null;
using (MemoryStream ms = new MemoryStream(cipheredData))
{
// Get salt
byte[] salt = new byte[8];
ms.Seek(8, SeekOrigin.Begin);
ms.Read(salt, 0, 8);
// Derive key and IV
OpenSslCompat.OpenSslCompatDeriveBytes db = new OpenSslCompat.OpenSslCompatDeriveBytes(passphrase, salt, "MD5", 1);
byte[] key = db.GetBytes(32);
byte[] iv = db.GetBytes(16);
using (Aes aes = Aes.Create())
{
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
aes.Key = key;
aes.IV = iv;
// Decrypt
ICryptoTransform decipher = aes.CreateDecryptor(aes.Key, aes.IV);
using (CryptoStream cs = new CryptoStream(ms, decipher, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs, Encoding.UTF8))
{
decrypted = sr.ReadToEnd();
}
}
}
}
return decrypted;
}
Note that the 2nd parameter of DecryptAesCbc is the passphrase (as string) and not the key (as byte[]). Also note that StreamReader uses an encoding (UTF-8 by default), which requires compatible data (i.e. text data, but this should be met for csv files). Otherwise (i.e. for binary data as opposed to text data) StreamReader must not be used.

How to decrypt a word which have more than 16 letters in Rijndael encryption

I made a Encryption program using Rijndael in C# after watching a video in youtube.It's very simple.
Interface picture
I can enter 64 bit and 128 bit keys. but 192 bit keys are not allowed (Why? ).
And if I use 64 bit key, when I encrypt a word and try to decrypt it back it only decrypts word with character count <= 16. it the character count is more than 16 an error messages thrown saysing "Padding is Invalid and cannot be removed".
Same goes for a 128 bit key. Only word with character count <=32 is decrypted back. otherwise same error message is displayed.
Here's a summery to take a clear view of the question
Problem Summery picture
Here's the code for Encryption
// need using System.Security.Cryptography;
// using System.IO;
public Form1()
{
InitializeComponent();
desObj = Rijndael.Create();
}
string cipherData;
byte[] chipherbytes;
byte[] plainbyte;
byte[] plainbyte2;
byte[] plainkey;
SymmetricAlgorithm desObj;
private void button2_Click(object sender, EventArgs e)
{
try
{
cipherData = textBox1.Text;
plainbyte = Encoding.ASCII.GetBytes(cipherData);
plainkey = Encoding.ASCII.GetBytes(textBox4.Text);
desObj.Key = plainkey;
//choose any method
desObj.Mode = CipherMode.CBC;
desObj.Padding = PaddingMode.PKCS7;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, desObj.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(plainbyte, 0, plainbyte.Length);
cs.Close();
chipherbytes = ms.ToArray();
ms.Close();
textBox2.Text = Encoding.ASCII.GetString(chipherbytes);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and the decyption code is
private void button3_Click(object sender, EventArgs e)
{
try
{
MemoryStream ms1 = new MemoryStream(chipherbytes);
CryptoStream cs1 = new CryptoStream(ms1, desObj.CreateDecryptor(), CryptoStreamMode.Read);
cs1.Read(chipherbytes, 0, chipherbytes.Length);
plainbyte2 = ms1.ToArray();
cs1.Close();
ms1.Close();
textBox3.Text = Encoding.ASCII.GetString(plainbyte2);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Ciphertext consists of arbitrary bytes which do not have to make up a valid ASCII encoding. If there are some non-printable ASCII characters, they will not be printed when used in this way: Encoding.ASCII.GetString(chipherbytes).
You need to encode the ciphertext with something like Base64 or Hex which will make the encoded ciphertext larger, but is perfectly representable as a printed string.
Other considerations:
CBC mode needs an initialization vector (IV) and since you're not setting any IV, it will be generated for you. The problem is that you need the same IV during decryption. This code works, because you're using the same desObj for encryption and decryption and it contains the same IV, but that's not going to work when you start copying ciphertext around.
The IV is not supposed to be secret. A common way is to pass it along with the ciphertext by writing the IV in front of it and slicing it off before decryption.
You're not having any integrity checking. It is better to authenticate your ciphertexts so that attacks like a padding oracle attack are not possible and you can detect whether the ciphertext was (maliciously) tampered with or the key was typed in incorrectly. This can be done with authenticated modes like GCM or EAX, or with an encrypt-then-MAC scheme.
Rijndael commonly supports key sizes of 128, 192 and 256 bit. A byte usually has 8 bits, so that amounts to 16, 24 and 32 byte keys.
Keys are not typed in by the user, because they usually need to be indistinguishable from random noise and of specific length. It is better to let users type in a password and derive the key from that with something like PBKDF2, bcrypt, scrypt or Argon2 using a high iteration count / cost factor.

How decrypt string in c# was encrypted in iOS using Rijndael

I'm trying to encrypt and decrypt the string using objective c and C#. both are working fine in native code, but when I was try to decrypt string in c# was encrypted in iOS. I get some error.
This was the code I used in the objective c
- (NSData *)AES256EncryptWithKey:(NSString *)key Data: (NSData *) data
{
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [data length];
NSData *iv = [#"abcdefghijklmnopqrstuvwxyz123456" dataUsingEncoding:NSUTF8StringEncoding];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
[iv bytes] /* initialization vector (optional) */,
[data bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess)
{
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
In want to know how to decrypt in C#, I give blocksize is 256, ivsize to 32 and used "RijndaelManaged()". I'm not using salt & password.
Error: something like "Padding is invalid and cannot be removed."
I tried to set padding too like PKCS7, none, zero but nothing help to decrypt.
can any one help this?
Edit:
My C# code here
public string DecryptString(string encrypted)
{
string result = null;
_encoder = new UTF8Encoding();
if (!string.IsNullOrWhiteSpace(encrypted) && (encrypted.Length >= 32))
{
var messageBytes = Convert.FromBase64String(encrypted);
using (var rm = new RijndaelManaged())
{
rm.BlockSize = _blockSize;
rm.Key = _encoder.GetBytes("mykey_here");
rm.IV = _encoder.GetBytes("abcdefghijklmnopqrstuvwxyz123456"); ;
rm.Padding = PaddingMode.Zeros;
var decryptor = rm.CreateDecryptor(rm.Key, messageBytes.Take(_ivSize).ToArray());
result = _encoder.GetString(Transform(messageBytes.Skip(_ivSize).ToArray(), decryptor));
}
}
return result;
}
protected byte[] Transform(byte[] buffer, ICryptoTransform transform)
{
byte[] result;
using (var stream = new MemoryStream())
using (var cs = new CryptoStream(stream, transform, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
cs.FlushFinalBlock();
result = stream.ToArray();
}
return result;
}
iOS (Common Crypto) explicitly specifies all encryption parameters, the C# code implicitly determines many parameters. These implicit parameters while simplifying usage are problematic when trying to achieve interoperability.
The C# class RijndaelManaged allows explicitly specifying parameter, change your code to use these, in particular BlockSize (128), KeySize (128), Mode (CipherMode.CBC) and Padding (PaddingMode.PKCS7). The defaults for mode and Padding are OK. See RijndaelManaged Documentation
AES and Rijndael are not the same, in particular AES uses only a block size of 128 bits (16 bytes) and Rijndael allows several block sizes. So one needs to specify a block size of 128 bits for Rijndael. Thus the iv is also 128 bits (16 bytes).
Both support encryption keys of 128, 192 and 256 bytes.
You would probably be better off using the AESManaged class than the RijndaelManaged class. See AesManaged Documentation
The C# side expects the data to be Base64 encoded, the iOS side does not show that encoding operation, make sure that is being done on the iOS side.
Since you are using an iv make sure you are using CBC mode on both sides. In Common Crypto CBC mode is the default, make sure CBC mode is being used on the C# side.
Make sure the C# side is using PKCS#7 or PKCS#5 padding, they are equivalent. It appears that PKCS#7 is the default on the C# side so this should be OK.
It is best to use a key of exactly the size specified and not rely on default padding. In Common Crypto the key size is explicitly specified and null padded if the supplied key is to short. The C# looks like it is determining the key size by the supplied key, in this case the key is 10 bytes so the decryption key probably defaults to 128 bits and the key is being internally padded with nulls. On iOS you are explicitly specifying a key size of 256 bits. This is a mis-match that needs to be fixed. Supply a key that is the exact size specified on the iOS side.
Finally there is the iv, the C# code expects the iv to be prepended to the encrypted data but the iOS code is not providing that. The solution is to change the iOS code to prepend the iv to the encrypted code. Change the iv to be 16 bytes, the AES block size.
Finally provide hex dumps of the test data in, data out, iv and key just prior to and after the encryption call if you need more help.

AES _Encryption in Mysql , Decryption in C#.Net

Mysql :
SELECT AES_ENCRYPT('Test','pass')
AES_ENCRYPT() and AES_DECRYPT() enable encryption and decryption of data using the official AES (Advanced Encryption Standard) algorithm, previously known as “Rijndael.” Encoding with a 128-bit key length is used, but you can extend it up to 256 bits by modifying the source. We chose 128 bits because it is much faster and it is secure enough for most purposes.
http://dev.mysql.com/doc/refman/5.5/en/encryption-functions.html#function_aes-encrypt
I was trying to convert that Encrypted string into Decryped Strig in C#.net but i don't get the results as i expect.
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx#Y0
C#
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
In this method I pass ciphertext,Key value which i usedfrom Mysql and
Rijndael.Create().IV for byte[] IV
I use the code but i don't get expected result.
Review the code and comment Idk where made a mistake
What you are doing is following a road of pain. Either decrypt/encrypt on MySQL and use an encrypted connection to the database (if that matters) or encrypt/decrypt on your .NET application, storing the encrypted data in a suitable column.
Mixing AES implementations is prone to mistakes and things can break more easily if you change versions of .NET or MySQL.
Now, to know what exactly is wrong we need to know if the IV is compatible between MySQL and .NET, or else find out what is MySQL's implementation IV and supply that.
And the other potential source of problems is how you have generated the byte arrays (we are not seeing that in your example). You have to consider character encoding issues in generating the arrays if the key is textual.
In the comments of this MySQL docs link there is information about the missing parameters.
After a long hours, I found a solution to this issue.
Couple of FYI's:
MySQL as a default for AES_Encrypt uses 128 bit, with ECB mode, which does not require an IV.
What padding mode they use is not specified, but they do say they pad it. For padding I use PaddingMode.Zeros.
In C#, use AesManaged, not RijndaelManaged since that is not recommended anymore.
If your Key is longer than 128 bits (16 bytes), then use a function below to create the correct key size, since the default MySQL AES algorithm uses 128 bit keys.
Make sure you play around with the correct Encoding and know exactly what type of character encoding you will receive back when translating the bytes to characters.
For more info go here: https://forums.mysql.com/read.php?38,193084,195959#msg-195959
Code:
public static string DecryptAESStringFromBytes(byte[] encryptedText, byte[] key)
{
// Check arguments.
if ((encryptedText == null || encryptedText.Length <= 0) || (key == null || key.Length <= 0))
{
throw new ArgumentNullException("Missing arguments");
}
string decryptedText = null;
// Create an AES object with the specified key and IV.
using (AesManaged aesFactory = new AesManaged())
{
aesFactory.KeySize = 128;
aesFactory.Key = AESCreateKey(key, aesFactory.KeySize / 8);
aesFactory.IV = new byte[16];
aesFactory.BlockSize = 128;
aesFactory.Mode = CipherMode.ECB;
aesFactory.Padding = PaddingMode.Zeros;
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = aesFactory.CreateDecryptor();
// Create the streams used for decryption.
using (MemoryStream stream = new MemoryStream())
{
using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Write))
{
decryptStream.Write(encryptedText, 0, encryptedText.Length);
}
decryptedText = Encoding.Default.GetString(stream.ToArray());
}
}
return decryptedText.Trim();
}
public static byte[] AESCreateKey(byte[] key, int keyLength)
{
// Create the real key with the given key length.
byte[] realkey = new byte[keyLength];
// XOR each byte of the Key given with the real key until there's nothing left.
// This allows for keys longer than our Key Length and pads short keys to the required length.
for (int i = 0; i < key.Length; i++)
{
realkey[i % keyLength] ^= key[i];
}
return realkey;
}
Here is some working code for achieving the same encryption via C# as MySQL:
public byte[] AESEncrypt(byte[] plaintext, byte[] key) {
/*
* Block Length: 128bit
* Block Mode: ECB
* Data Padding: Padded by bytes which Asc() equal for number of padded bytes (done automagically)
* Key Padding: 0x00 padded to multiple of 16 bytes
* IV: None
*/
RijndaelManaged aes = new RijndaelManaged();
aes.BlockSize = 128;
aes.Mode = CipherMode.ECB;
aes.Key = key;
ICryptoTransform encryptor = aes.CreateEncryptor();
MemoryStream mem = new MemoryStream();
CryptoStream cryptStream = new CryptoStream(mem, encryptor,
CryptoStreamMode.Write);
cryptStream.Write(plaintext, 0, plaintext.Length);
cryptStream.FlushFinalBlock();
byte[] cypher = mem.ToArray();
cryptStream.Close();
cryptStream = null;
encryptor.Dispose();
aes = null;
return cypher;
}
For details see MySQL Bug # 16713
EDIT:
Since the above is relying on officially non-documented information (though it is working) I would recommend to avoid it and use one of the options described in the answer from Vinko Vrsalovic .
If you run SELECT AES_ENCRYPT('Test','pass')
your are sending the pass over the network unencrypted so any one can unencrypted the data.
The AES_ENCRYPT is used to store data so if the database gets hacked your data is safe, not to transmit data.
if you want data encryption over the net work connect to your mysql server using the ssl socket

C# AES-256 Encryption

I am using RijndaelManaged to make a simple encryption/decryption utility. This is working fine, but I am trying to get it integrated with another program which is created in Unix (Oracle). My problem is, for all smaller input string, i am getting the exact same encrypted hex as the Unix code is generation, but for longer strings, half of my encrypted hex is same, but the other half is different:
Unix Output:
012345678901234 - 00984BBED076541E051A239C02D97117
0123456789012345678 - A0ACE158AD8CF70CEAE8F76AA27F62A30EA409ECE2F7FF84F1A9AF50817FC0C4
Windows Output (my code):
012345678901234 - 00984BBED076541E051A239C02D97117 (same as above)
0123456789012345678 - A0ACE158AD8CF70CEAE8F76AA27F62A3D9A1B396A614DA2C1281AA1F48BC3EBB (half exactly same as above)
My Windows code is:
public string Encrypt(byte[] PlainTextBytes, byte[] KeyBytes, string InitialVector)
{
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.ECB;
SymmetricKey.Padding = PaddingMode.PKCS7;
ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes);
MemoryStream MemStream = new MemoryStream();
CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write);
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
CryptoStream.FlushFinalBlock();
byte[] CipherTextBytes = MemStream.ToArray();
MemStream.Close();
CryptoStream.Close();
return ByteToHexConversion(CipherTextBytes);
}
Unix (PL/SQL) code:
FUNCTION Encrypt_Card (plain_card_id VARCHAR2)
RETURN RAW AS
num_key_bytes NUMBER := 256/8; -- key length 256 bits (32 bytes)
encrypted_raw RAW (2000); -- stores encrypted binary text
encryption_type PLS_INTEGER := -- total encryption type
DBMS_CRYPTO.ENCRYPT_AES256
+ DBMS_CRYPTO.CHAIN_CBC
+ DBMS_CRYPTO.PAD_PKCS5;
key_bytes_raw RAW(64) :=my_hex_key;
BEGIN
encrypted_raw := DBMS_CRYPTO.ENCRYPT
(
src => UTL_I18N.STRING_TO_RAW (plain_card_id, 'AL32UTF8'),
typ => encryption_type,
key => key_bytes_raw
);
RETURN encrypted_raw;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line (plain_card_id || ' - ' || SUBSTR(SQLERRM,1,100) );
RETURN HEXTORAW ('EEEEEE');
The only difference i see is use of PKCS5 and PCKS7. But, .NET doesn't have PCKS5.
What abc said and also you don't seem to have any IV (Initialization Vector) in you PL/SQL code at all.
The fact that the first part are the same has to do with the different modes (ECB and CBC). ECB encrypts each block separately while CBC uses the previous block when encrypting the next one.
What happens here is that since you use CBC and do not set an IV the IV is all zeroes.
That means that the first block of ECB encryption and CBC encryption will be the same.
(Since A XOR 0 = A).
You need to make sure you use the same encryption mode in both systems and if you decide on CBC make sure you use the same IV.
You use ECB in one case and CBC in the other case.

Categories