I have a problem. I have a method to encrypt a password in php and in C# but i cannot get the same results with both algorithms. Someone can help me?
PhP
<?php
$password = 'MySecretPass';
$secret = '65rgt85k89xrDAr3';
$iv = 'AAAAAAAAAAAAAAAA';
$td = mcrypt_module_open('rijndael-128', '', 'cfb','');
mcrypt_generic_init($td, $secret, $iv);
$password = mcrypt_generic($td, $password);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$password=base64_encode($password);
echo $password;
?>
C#
var password = padString("MySecretPass");
txtEncrypt.Text = Convert.ToBase64String(EncryptStringToBytes(password,
Encoding.UTF8.GetBytes("65rgt85k89xrDAr3"),
Encoding.UTF8.GetBytes("AAAAAAAAAAAAAAAA"), PaddingMode.None));
txtEncrypt.Text = txtEncrypt.Text;
static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv, PaddingMode mode)
{
byte[] encrypted;
using (var rijAlg = new RijndaelManaged { Mode = CipherMode.CFB, BlockSize = 128, Padding = mode })
{
rijAlg.Key = key;
rijAlg.IV = iv;
var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
private static String padString(String source)
{
char paddingChar = ' ';
int size = 16;
int x = source.Length % size;
int padLength = size - x;
for (int i = 0; i < padLength; i++)
{
source += paddingChar;
}
return source;
}
The results for PhP is "/KNlzi/fZOERWL79", but for c# is /J643dvAR4/Gh0aYHdshNw==. I don't know why my results are different. In addition, I have wrote the code in Java and I get the same result than in C#.
Thanks in advance.
It's probably that Encoding.GetBytes(string) returns "Unicode encoding". That's an encoding that actually does not exist, but it returns UTF-16. On the other hand you treat your key and IV as ASCII characters.
So whichever encoding PHP is using at the time, there will be a mismatch. You should explicitly define which encoding should be used when converting textual strings to bytes, both in the PHP code as in your C# code.
Related
I'm trying to decrypt AES-128 CBC strings in C# but with no success (tried every decrypt method I found on internet for this type of encryption).
The only way I got a result was decrypting those strings in PHP using this code:
<?php
$crypto_data = hex2bin($crypto_data_hex);
$real_data = openssl_decrypt($crypto_data,
'AES-128-CBC',
'23d854ce7364b4f7',
OPENSSL_RAW_DATA,
'23d854ce7364b4f7');
?>
So, is there a way to run this PHP code in .NET (using a PHP.dll library or something similar) ? Or is there a real equivalent method for this operation in .NET C# ?
Thank you
The question seems to boil down to writing C# function that is equivalent to PHP function.
Try this code:
public class Program
{
public static byte[] HexToBytes(string hex)
{
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;
}
static string Decrypt(byte[] cipherText, byte[] key, byte[] iv)
{
string plaintext;
AesManaged aes = new AesManaged
{
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
BlockSize = 128,
Key = key,
IV = iv
};
using (aes)
{
ICryptoTransform decryptor = aes.CreateDecryptor();
using (MemoryStream ms = new MemoryStream(cipherText))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cs))
{
plaintext = reader.ReadToEnd();
}
}
}
}
return plaintext;
}
public static void Main()
{
string crypto_data_hex = "00965fa56e761b11d37b887f98e6bcc2"; // paste $crypto_data_hex value here
string sKey = "23d854ce7364b4f7";
string sIv = "23d854ce7364b4f7";
byte[] encrypted = HexToBytes(crypto_data_hex);
byte[] key = Encoding.ASCII.GetBytes(sKey);
byte[] iv = Encoding.ASCII.GetBytes(sIv);
string decrypted = Decrypt(encrypted, key, iv);
Console.WriteLine(decrypted);
}
}
I'm building a simple PHP script that need to decode input from C# application.
I've created C# app with below encrypting function (I've also included my decrypting function):
public static string Encrypt(string input, string key)
{
var aes = new RijndaelManaged
{
KeySize = 256,
BlockSize = 256,
Padding = PaddingMode.PKCS7,
Mode = CipherMode.CBC,
Key = Encoding.UTF8.GetBytes(key)
};
aes.GenerateIV();
var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] buffer;
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
byte[] bytes = Encoding.UTF8.GetBytes(input);
cs.Write(bytes, 0, bytes.Length);
}
buffer = ms.ToArray();
}
buffer = buffer.Concat(aes.IV).ToArray();
return Convert.ToBase64String(buffer);
}
private static String Decrypt(string text, string key)
{
RijndaelManaged aes = new RijndaelManaged
{
KeySize = 256,
BlockSize = 256,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
Key = Encoding.UTF8.GetBytes(key)
};
byte[] encoded = Convert.FromBase64String(text);
byte[] buffer = encoded.Take(encoded.Length - aes.IV.Length).ToArray();
aes.IV = encoded.Skip(encoded.Length - aes.IV.Length).ToArray();
var decrypt = aes.CreateDecryptor();
byte[] xBuff;
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
}
xBuff = ms.ToArray();
}
var output = Encoding.UTF8.GetString(xBuff);
return output;
}
After couple of minutes of searching I've found simple decryption function in PHP using mcrypt:
function strippadding($string)
{
$slast = ord(substr($string, -1));
$slastc = chr($slast);
$pcheck = substr($string, -$slast);
if(preg_match("/$slastc{".$slast."}/", $string)){
$string = substr($string, 0, strlen($string)-$slast);
return $string;
} else {
return false;
}
}
function decrypt($string, $key)
{
$string = base64_decode($string);
$iv = substr($string, -32);
$string = str_replace($iv, "", $string);
return strippadding(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $string, MCRYPT_MODE_CBC, $iv));
}
This works well, but as I read on multiple sites, mcrypt is no longer recommended and sooner or later will be removed.
I'm trying to recreate same function using openssl, but without any luck.
I've tried replacing mcrypt_decrypt with:
openssl_decrypt($string, 'aes-256-cbc', $encryption_key, 0, $iv);
but as I found out MCRYPT_RIJNDAEL_256 doesn't mean AES-256.
I've been trying with different key size and block size, but without luck.
How can I recreate PHP decrypting function using openssl?
EDIT1 :
I've changed RijndaelManaged with AesCryptoServiceProvider in my C# code:
var aes = new AesCryptoServiceProvider()
{
KeySize = 256,
BlockSize = 128,
Padding = PaddingMode.PKCS7,
Mode = CipherMode.CBC,
Key = Encoding.UTF8.GetBytes(key)
};
and inside PHP to:
define('AES_128_CBC', 'aes-128-cbc');
function decrypt_openssl($string, $pkey)
{
$key = $pkey;
$string = base64_decode($string);
$iv = substr($string, -32);
$string = str_replace($iv, "", $string);
$decrypted = openssl_decrypt($string, AES_128_CBC, base64_encode($key), 0, base64_encode($iv));
return $decrypted;
}
but still I can't get encoded string to be decoded in PHP.
I need a way to decrypt output of my C# function or change both to get that two way communication working.
EDIT2:
I'm providing full source of my C# class:
public static string EncryptRijndael(string input, string key)
{
var aes = new RijndaelManaged
{
KeySize = 256,
BlockSize = 256,
Padding = PaddingMode.PKCS7,
Mode = CipherMode.CBC,
Key = Encoding.UTF8.GetBytes(key)
};
aes.GenerateIV();
var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] buffer;
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
byte[] bytes = Encoding.UTF8.GetBytes(input);
cs.Write(bytes, 0, bytes.Length);
}
buffer = ms.ToArray();
}
buffer = buffer.Concat(aes.IV).ToArray();
aes.Dispose();
return Convert.ToBase64String(buffer);
}
public static string DecryptRijndael(string input, string key)
{
var aes = new RijndaelManaged
{
KeySize = 256,
BlockSize = 256,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
Key = Encoding.UTF8.GetBytes(key)
};
byte[] xXml = Convert.FromBase64String(input);
var buffer = xXml.Take(xXml.Length - aes.IV.Length).ToArray();
var iv = xXml.Skip(xXml.Length - aes.IV.Length).ToArray();
aes.IV = iv;
var decrypt = aes.CreateDecryptor();
byte[] xBuff;
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
}
xBuff = ms.ToArray();
}
aes.Dispose();
String output = Encoding.UTF8.GetString(xBuff);
return output;
}
public static string EncryptAes(string input, string key)
{
var aes = new AesCryptoServiceProvider()
{
KeySize = 256,
BlockSize = 128,
Padding = PaddingMode.PKCS7,
Mode = CipherMode.CBC,
Key = Encoding.UTF8.GetBytes(key)
};
aes.GenerateIV();
var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] buffer;
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
byte[] bytes = Encoding.UTF8.GetBytes(input);
cs.Write(bytes, 0, bytes.Length);
}
buffer = ms.ToArray();
}
buffer = buffer.Concat(aes.IV).ToArray();
aes.Dispose();
return Convert.ToBase64String(buffer);
}
public static String DecryptAes(string input, string key)
{
var aes = new AesCryptoServiceProvider()
{
KeySize = 256,
BlockSize = 128,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
Key = Encoding.UTF8.GetBytes(key)
};
byte[] xXml = Convert.FromBase64String(input);
var buffer = xXml.Take(xXml.Length - aes.IV.Length).ToArray();
var iv = xXml.Skip(xXml.Length - aes.IV.Length).ToArray();
aes.IV = iv;
var decrypt = aes.CreateDecryptor();
byte[] xBuff;
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
}
xBuff = ms.ToArray();
}
aes.Dispose();
String output = Encoding.UTF8.GetString(xBuff);
return output;
}
My test key is: zjPUcCp9Jn7k8RtEzxTRePjn984LqwyN
My test data as plain text: zażółć geślą jaźń
My test data as base64: emHFvMOzxYLEhyBnZcWbbMSFIGphxbrFhA==
And sample output for both encryption functions:
Rijndael: 4gD/tt3I3hqYToLnwxI/HJ37EHfXrd1uxchIOjuxSuZl0Kyvxb+S6h4gG3cWKJTbj0wDSH1zvbeSvHd9Wu1VaA==
AES: B0dKdL4k9J6CeqlAekaXM+eh/zDqd5B4sKK2p6DFsgYNbV56Xdy01XvYPZX8ZXBc
IV is added at the end of byte array just before creating base64 output. When decrypting I'm reading IV from end of input string and using it to decrypt.
I need to ensure I can encrypt/decrypt utf-8 strings.
This is not an answer but added as an answer because of necessary formatting and length:
Provided by the OP:
Encryption input:
test key is: zjPUcCp9Jn7k8RtEzxTRePjn984LqwyN
test data as plain text: zażółć geślą jaźń (not used, see below)
test data as base64: emHFvMOzxYLEhyBnZcWbbMSFIGphxbrFhA== (used)
Sample output for both encryption functions:
Rijndael: 4gD/tt3I3hqYToLnwxI/HJ37EHfXrd1uxchIOjuxSuZl0Kyvxb+S6h4gG3cWKJTbj0wDSH1zvbeSvHd9Wu1VaA==
AES: B0dKdL4k9J6CeqlAekaXM+eh/zDqd5B4sKK2p6DFsgYNbV56Xdy01XvYPZX8ZXBc
Provided data displayed as hex for consistency, spaces added for legibility:
RijndaelExpected: e200ffb6 ddc8de1a 984e82e7 c3123f1c 9dfb1077 d7addd6e c5c8483a 3bb14ae6 65d0acaf c5bf92ea 1e201b77 162894db 8f4c0348 7d73bdb7 92bc777d 5aed5568
AESExpected: 07474a74 be24f49e 827aa940 7a469733 e7a1ff30 ea779078 b0a2b6a7 a0c5b206 0d6d5e7a 5ddcb4d5 7bd83d95 fc65705c
testData: 7a61c5bc c3b3c582 c4872067 65c59b6c c485206a 61c5bac5 84
testKey: 7a6a5055 63437039 4a6e376b 38527445 7a785452 65506a6e 3938344c 7177794e
testIV: 8f4c0348 7d73bdb7 92bc777d 5aed5568 (from RijndaelExpected trailing bytes).
The above is what one would hope for in a question.
Assumptions: PKCS#7 padding, CBC mode.
Based on the data 7-bytes of padding is expected so the encrypted data should be 32-bytes.
The RijndaelExpected output is 64-bytes, minus 16-bytes for the appended IV is 48-bytes which is incorrect.
The AESExpected output is 48-bytes. If the IV is appended it does not match RijndaelExpected, it the IV is not appended it is the wrong length.
My calculated AES output without an appended IV is (Note an IV generally prefixes the encrypted data):
CryptData: 1a6ec05d 00a6e61b 8196e7f2 879e2f59 25d3b7e2 c103f7e6 41c8c93f 70b32de5
Which does not agree with either expected output.
Also see this online AES calculator Note that PKCS#7 padding has been manually added.
For completness only, my test code:
NSData *testData = [[NSData alloc] initWithBase64EncodedString:#"emHFvMOzxYLEhyBnZcWbbMSFIGphxbrFhA==" options:0];
NSData *testKey = [#"zjPUcCp9Jn7k8RtEzxTRePjn984LqwyN" dataUsingEncoding:NSUTF8StringEncoding];
NSData *testIV = [[NSData alloc] initWithBase64EncodedString:#"j0wDSH1zvbeSvHd9Wu1VaA==" options:0];
size_t movedBytes = 0;
NSMutableData *cryptData = [NSMutableData dataWithLength: testData.length + kCCBlockSizeAES128];
CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
kCCOptionPKCS7Padding, // CBC mode is the default
testKey.bytes, kCCKeySizeAES256,
testIV.bytes,
testData.bytes, testData.length,
cryptData.mutableBytes, cryptData.length,
&movedBytes);
cryptData.length = movedBytes;
Display(#"CryptData: %#", cryptData);
I'm having a bit of an issue encrypting / decrypting cross languages.
Here is my python code to encrypt some text:
class AESCipher:
def __init__( self, key, iv ):
self.key = base64.b64decode(key)
self.iv = base64.b64decode(iv)
def encrypt( self, raw ):
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
raw = pad(raw)
cipher = AES.new( self.key, AES.MODE_CBC, self.iv)
res = self.iv + cipher.encrypt( raw )
return base64.b64encode(res)
def decrypt( self, enc ):
enc = base64.b64decode(enc)
unpad = lambda s : s[:-ord(s[len(s)-1:])]
cipher = AES.new(self.key, AES.MODE_CBC, self.iv )
return unpad(cipher.decrypt( enc[16:] ))
crypt = AESCipher("key", "iv")
print "{0}".format(crypt.encrypt("Hallow"))
And C# Decrypting:
public static string DecryptStringFromBase64(string base64String)
{
byte[] bytes = Decrypt(Convert.FromBase64String(base64String));
var utf8 = Encoding.UTF8.GetString(bytes);
return utf8;
}
public static byte[] Decrypt(byte[] bytes)
{
AesManaged algorithm = new AesManaged();
algorithm.IV = Convert.FromBase64String("IV");
algorithm.Key = Convert.FromBase64String("KEY");
byte[] ret = null;
using (var decryptor = algorithm.CreateDecryptor())
{
using (MemoryStream msDecrypted = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msDecrypted, decryptor, CryptoStreamMode.Write))
{
csEncrypt.Write(bytes, 0, bytes.Length);
}
ret = msDecrypted.ToArray();
}
}
return ret;
}
However the decrypted value always comes out incorrectly like this:
I think this has something to do with the padding, can anybody suggest how to get around this?
The problem is not the padding. It's the IV that you haven't sliced off. The IV doesn't have to be secret, but it should be randomly generated for each encryption. Since you're already including the IV into the ciphertext in Python, you have to use it in C# during decryption (of course the decryption should be done on the actual ciphertext excluding the IV):
C#
public static string DecryptStringFromBase64(string base64String)
{
byte[] bytes = Decrypt(Convert.FromBase64String(base64String));
var utf8 = Encoding.UTF8.GetString(bytes);
return utf8;
}
public static byte[] Decrypt(byte[] bytes)
{
byte[] iv = new byte[16]; // change
Array.copy(bytes, iv, 16); // change
AesManaged algorithm = new AesManaged();
algorithm.IV = iv; // change
algorithm.Key = Convert.FromBase64String("KEY");
byte[] ret = null;
using (var decryptor = algorithm.CreateDecryptor())
{
using (MemoryStream msDecrypted = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msDecrypted, decryptor, CryptoStreamMode.Write))
{
csEncrypt.Write(bytes, 16, bytes.Length - 16); // change
}
ret = msDecrypted.ToArray();
}
}
return ret;
}
The Python code is also not without its issues. You don't need to pass in the IV, because you're putting it into the ciphertext. So you can just create a new random IV. Additionally, the unpad function is not correct (or at least needlessly complicated).
class AESCipher:
def __init__( self, key):
self.key = base64.b64decode(key)
def encrypt( self, raw ):
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
raw = pad(raw)
iv = Random.new().read(BS)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
res = iv + cipher.encrypt( raw )
return base64.b64encode(res)
def decrypt( self, enc ):
enc = base64.b64decode(enc)
BS = 16
iv = enc[:BS]
unpad = lambda s : s[:-ord(s[-1])]
cipher = AES.new(self.key, AES.MODE_CBC, iv )
return unpad(cipher.decrypt( enc[BS:] ))
crypt = AESCipher("key", "iv")
print "{0}".format(crypt.encrypt("Hallow"))
Don't forget to authenticate your ciphertexts. Otherwise, a padding oracle attack might be launched against your system which enables an attack to decrypt every ciphertext with multiple online queries.
You can use an authenticated modes like GCM or EAX, or employ an encrypt-then-MAC scheme with a strong MAC like HMAC-SHA256.
I want to make an encrypted communication system with a dynamic key exchange between C# and PHP. At the moment I have a working encrypt/decrypt PHP <-> PHP and C# <-> C# but it's not working PHP <-> C# for some reason. The problem is that the C# code decrypted string generates a longer output than the PHP would expect, but the data is the same when viewing the output as a simple string. E.g a string "daa" sent from C# to PHP, decrypted length is 28, which is not what is supposed to be. Same goes with the string sent from PHP to C#, I get a compiler error ArgumentException: length
C# code:
public static string EncryptTest(string input)
{
string key = "256 bit key (32 char)";
input = Md5Sum(input).Substring(0, 4) + input;
var encoding = new UTF8Encoding();
var Key = encoding.GetBytes(key);
byte[] encrypted;
byte[] result;
using (var rj = new RijndaelManaged())
{
try
{
rj.Padding = PaddingMode.PKCS7;
rj.Mode = CipherMode.CBC;
rj.KeySize = 256;
rj.BlockSize = 256;
rj.Key = Key;
rj.GenerateIV();
using (ICryptoTransform encryptor = rj.CreateEncryptor())
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(cs))
{
writer.Write(input);
}
}
encrypted = ms.ToArray();
result = new byte[rj.BlockSize / 8 + encrypted.Length];
// Result is built as: IV (plain text) + Encrypted(data)
Array.Copy(rj.IV, result, rj.BlockSize / 8);
Array.Copy(encrypted, 0, result, rj.BlockSize / 8, encrypted.Length);
}
}
}
finally
{
rj.Clear();
}
}
return Convert.ToBase64String(result);
}
public static string DecryptTest(string input)
{
string key = "256 bit key (32 char)";
byte[] data = Convert.FromBase64String(input);
if (data.Length < 32)
return null;
var encoding = new UTF8Encoding();
var Key = encoding.GetBytes(key);
using (RijndaelManaged aes = new RijndaelManaged())
{
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
aes.KeySize = 256;
aes.BlockSize = 256;
aes.Key = Key;
// Extract the IV from the data first.
byte[] iv = new byte[aes.BlockSize / 8];
Array.Copy(data, iv, iv.Length);
aes.IV = iv;
// The remainder of the data is the encrypted data we care about.
byte[] encryptedData = new byte[data.Length - iv.Length];
Array.Copy(data, iv.Length, encryptedData, 0, encryptedData.Length);
using (ICryptoTransform decryptor = aes.CreateDecryptor())
{
using (MemoryStream ms = new MemoryStream(encryptedData))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cs))
{
string output = reader.ReadToEnd();
if (output.Length < 4)
return null;
string dataHash = output.Substring(0, 4);
string dataInput = output.Substring(4);
string dataInputHash = Md5Sum(dataInput).Substring(0, 4);
if (dataHash != dataInputHash)
return null;
return dataInput;
}
}
}
}
}
}
private static string Md5Sum(string strToEncrypt)
{
UTF8Encoding ue = new UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] hashBytes = md5.ComputeHash(bytes);
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
PHP code:
$key = "256 bit key (32 char)";
function iv()
{
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
return mcrypt_create_iv($iv_size, MCRYPT_RAND);
}
function encrypt($data, $key32)
{
# Prepend 4-chars data hash to the data itself for validation after decryption
$data = substr(md5($data), 0, 4).$data;
# Prepend $iv to decrypted data
$iv = iv();
$enc = $iv.mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key32, $data, MCRYPT_MODE_CBC, $iv);
return base64_encode($enc);
}
function decrypt($data, $key32)
{
$data = base64_decode($data);
if ($data === false || strlen($data) < 32)
return null;
$iv = substr($data, 0, 32);
$encrypted = substr($data, 32);
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key32, $encrypted, MCRYPT_MODE_CBC, $iv), "\0");
if ($decrypted === false || is_null($decrypted) || strlen($decrypted) < 4)
return null;
$dataHash = substr($decrypted, 0, 4);
$data = substr($decrypted, 4);
if (substr(md5($data), 0, 4) !== $dataHash)
return null; // it breaks here, md5 sum is not correct because of the length
return $data;
}
PHP / mcrypt is not using PKCS#7 padding, it uses zero padding of 0..n bytes where n is the block size.
To PKCS#7-pad the plaintext before encryption, use:
$pad = $blockSize - (strlen($data) % $blockSize);
$pdata = $data . str_repeat(chr($pad), $pad);
to unpad the plaintext after decryption simply perform:
$pad = ord($pdata[strlen($pdata) - 1]);
$data = substr($pdata, 0, strlen($pdata) - $pad);
PKCS#7 is now the ad hoc standard for padding. Zero padding is non-deterministic; it may alter the plaintext if the plaintext ends with zero's itself.
I am attempting to integrate Desk.com's Multipass SSO into my website, and am having trouble generating the correct HMAC-SHA1 signature (so say the error logs). Here are the directions from Desk.com's website:
Build a SHA1 HMAC using your multipass API key and your finished multipass token.
Base64 encode the resulting HMAC.
According to the logs, my multipass token appears to be correct. First, the code in PHP that works perfectly:
// Build an HMAC-SHA1 signature using the multipass string and your API key
$signature = hash_hmac("sha1", $multipass, $api_key, true);
// Base64 encode the signature
$signature = base64_encode($signature);
^ note that hash_hmac's 'true' value is outputting information in raw binary - I'm not sure if this is the case in my C# code
Next, my C# code that is not working correctly:
protected string getSignature(string multipass)
{
string api_key = "my_key_goes_here";
HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes(api_key));
hmac.Initialize();
byte[] buffer = Encoding.ASCII.GetBytes(multipass);
string signature = BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower();
return Convert.ToBase64String(Encoding.ASCII.GetBytes(signature));
}
This is the result of (literally) hours of searching and trying multiple different ways. I would be very grateful if I could get this figured out.
If you need a reference, check out this page by Desk.com: http://dev.desk.com/docs/portal/multipass. It has code examples and outlines the instructions for completing the code.
Edit: here is my multipass generation code.
protected string getMultipass(UserData user_data)
{
// Encode the data into a JSON object
JavaScriptSerializer s = new JavaScriptSerializer();
string json_data = s.Serialize(user_data);
// Acquire the Web.config appSettings
string site_key = "my_site_here";
string api_key = "my_key_here";
string iv = "OpenSSL for Ruby";
// Using byte arrays now instead of strings
byte[] encrypted = null;
byte[] bIV = Encoding.ASCII.GetBytes(iv);
byte[] data = Encoding.ASCII.GetBytes(json_data);
// XOR the first block (16 bytes)
// once before the full XOR
// so it gets double XORed
for (var i = 0; i < 16; i++)
data[i] = (byte)(data[i] ^ bIV[i]);
// Pad using block size of 16 bytes
int pad = 16 - (data.Length % 16);
Array.Resize(ref data, data.Length + pad);
for (var i = 0; i < pad; i++)
data[data.Length - pad + i] = (byte)pad;
// Use the AesManaged object to do the encryption
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.IV = bIV;
aesAlg.KeySize = 128;
// Create the 16-byte salted hash
SHA1 sha1 = SHA1.Create();
byte[] saltedHash = sha1.ComputeHash(Encoding.UTF8.GetBytes(api_key + site_key), 0, (api_key + site_key).Length);
Array.Resize(ref saltedHash, 16);
aesAlg.Key = saltedHash;
// Encrypt using the AES managed object
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
csEncrypt.Write(data, 0, data.Length);
csEncrypt.FlushFinalBlock();
}
encrypted = msEncrypt.ToArray();
}
}
// Return the Base64-encoded encrypted data
return Convert.ToBase64String(encrypted, Base64FormattingOptions.None)
.TrimEnd("=".ToCharArray()) // Remove trailing "=" characters
.Replace("+", "-") // Change "+" to "-"
.Replace("/", "_"); // Change "/" to "_"
}
You can see the following code that works:
static string create(string userDetails) {
string accountKey = "YOUR_ACCOUNT_KEY";
string apiKey = "YOUR_API_KEY";
string initVector = "OpenSSL for Ruby"; // DO NOT CHANGE
byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
byte[] keyBytesLong;
using( SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider() ) {
keyBytesLong = sha.ComputeHash( Encoding.UTF8.GetBytes( apiKey + accountKey ) );
}
byte[] keyBytes = new byte[16];
Array.Copy(keyBytesLong, keyBytes, 16);
byte[] textBytes = Encoding.UTF8.GetBytes(userDetails);
for (int i = 0; i < 16; i++) {
textBytes[i] ^= initVectorBytes[i];
}
// Encrypt the string to an array of bytes
byte[] encrypted = encryptStringToBytes_AES(textBytes, keyBytes, initVectorBytes);
string encoded = Convert.ToBase64String(encrypted);
return HttpUtility.UrlEncode(encoded);
}
static byte[] encryptStringToBytes_AES(byte[] textBytes, byte[] Key, byte[] IV) {
// Declare the stream used to encrypt to an in memory
// array of bytes and the RijndaelManaged object
// used to encrypt the data.
using( MemoryStream msEncrypt = new MemoryStream() )
using( RijndaelManaged aesAlg = new RijndaelManaged() )
{
// Provide the RijndaelManaged object with the specified key and IV.
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
aesAlg.KeySize = 128;
aesAlg.BlockSize = 128;
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create an encrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor();
// Create the streams used for encryption.
using( CryptoStream csEncrypt = new CryptoStream( msEncrypt, encryptor, CryptoStreamMode.Write ) ) {
csEncrypt.Write( textBytes, 0, textBytes.Length );
csEncrypt.FlushFinalBlock();
}
byte[] encrypted = msEncrypt.ToArray();
// Return the encrypted bytes from the memory stream.
return encrypted;
}
}
I hope it works for you.