I'm going to encrypt my data transferring between my multi platform apps. My question is that which algorithm can be used that work for all these platforms?
That should have these parameters:
Dynamic key and iv.
Supported in C#, Android, Swift, PHP.
Be secure enough.
It will be welcome if anybody give me some samples or links for each platform.
UPDATE:
I tried these classes:
Android:
public class Cryptor {
private IvParameterSpec ivspec;
private SecretKeySpec keyspec;
private Cipher cipher;
public Cryptor(byte[] key_par,byte[] iv_par)
{
keyspec = new SecretKeySpec(key_par, "AES");
ivspec = new IvParameterSpec(iv_par);
try {
cipher = Cipher.getInstance("AES/CBC/ZeroPadding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
public byte[] encrypt(byte[] input) throws Exception
{
if(text == null || text.length() == 0)
throw new Exception("Empty input");
byte[] encrypted = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
encrypted = cipher.doFinal(input);
} catch (Exception e)
{
throw new Exception("[encrypt] " + e.getMessage());
}
return encrypted;
}
public byte[] decrypt(String code) throws Exception
{
if(code == null || code.length() == 0)
throw new Exception("Empty string");
byte[] decrypted = null;
try {
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
decrypted = cipher.doFinal(hexToBytes(code));
} catch (Exception e)
{
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}
public static String bytesToHex(byte[] data)
{
if (data==null)
{
return null;
}
int len = data.length;
String str = "";
for (int i=0; i<len; i++) {
if ((data[i]&0xFF)<16)
str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
else
str = str + java.lang.Integer.toHexString(data[i]&0xFF);
}
return str;
}
public static byte[] hexToBytes(String str) {
if (str==null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i<len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
}
return buffer;
}
}
}
PHP:
class MCrypt
{
protected $in_iv;
protected $in_key;
function __construct($in_key , $in_iv)
{
$this->key = $in_key;
$this->iv = $in_iv;
}
function encrypt($str) {
$iv = $this->iv;
$td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);
mcrypt_generic_init($td, $this->key, $iv);
$encrypted = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return bin2hex($encrypted);
}
function decrypt($code) {
$code = $this->hex2bin($code);
$iv = $this->iv;
$td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);
mcrypt_generic_init($td, $this->key, $iv);
$decrypted = mdecrypt_generic($td, $code);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return utf8_encode(trim($decrypted));
}
protected function hex2bin($hexdata) {
$bindata = '';
for ($i = 0; $i < strlen($hexdata); $i += 2) {
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}
}
C#:
class Cryptor
{
private byte[] iv;
private byte[] key;
public Cypher(byte[] key, byte[] iv)
{
this.key = key;
this.iv = iv;
}
public byte[] EncryptRJ128(byte[] input)
{
var encoding = new UTF8Encoding();
byte[] encrypted;
using (var rj = new RijndaelManaged())
{
try
{
rj.Padding = PaddingMode.Zeros;
rj.Mode = CipherMode.CBC;
rj.KeySize = 128;
rj.BlockSize = 128;
rj.Key = key;
rj.IV = iv;
var ms = new MemoryStream();
var cs = new CryptoStream(ms, rj.CreateEncryptor(key, iv), CryptoStreamMode.Write);
var sr = new StreamWriter(cs);
sr.Write(input);
sr.Flush();
cs.FlushFinalBlock();
encrypted = ms.ToArray();
}
finally
{
rj.Clear();
}
}
return encrypted;
}
public String DecryptRJ128(byte[] input)
{
var sRet = "";
var encoding = new UTF8Encoding();
using (var rj = new RijndaelManaged())
{
try
{
rj.Padding = PaddingMode.Zeros;
rj.Mode = CipherMode.CBC;
rj.KeySize = 128;
rj.BlockSize = 128;
rj.Key = key;
rj.IV = iv;
var ms = new MemoryStream(input);
var cs = new CryptoStream(ms, rj.CreateDecryptor(key, iv), CryptoStreamMode.Read);
var sr = new StreamReader(cs);
sRet = sr.ReadLine();
}
finally
{
rj.Clear();
}
}
return sRet;
}
}
TEST:
This is some example that I used to test:
key ={ 106,104,103,97,103,94,115,106,102,96,115,53,53,52,55,53}
iv ={104,49,52,56,114,102,103,49,48,50,52,97,56,51,118,52}
input ={57,102,117,105,65,75,113,105,108,119,113,54,109,73,89,104}
Now trying to encrypt:
Android and PHP output:
170, 29, 170, 139, 14, 192, 81, 232, 41, 237, 25, 19, 130, 237, 15, 198
c# OUTPUT:
59 , 85 , 127 , 29 , 161 , 145 , 23 , 127 , 246 , 100 , 157 , 234 , 128 , 65
Related
I am trying to decrypt that from the database. The Data is encrypted from the SQL Server
reportItems.DisabilityGroup = Cryptography.ASPEncrypter(reportItems.DisabilityGroup, true);
The above code is when I invoke the decryption method. It works for small data but fails for more data. I get the following order
System.Security.Cryptography.CryptographicException: 'Length of the data to decrypt is invalid.'
private static string DoEncrypt(string Message)
{
// Encrypt string
byte[] Results;
var UTF8 = new UTF8Encoding();
using (var HashProvider = new MD5CryptoServiceProvider())
{
var TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(PassPhrase));
//var TDESAlgorithm = new TripleDESCryptoServiceProvider()
//{
// Key = TDESKey,
// Mode = CipherMode.ECB,
// Padding = PaddingMode.PKCS7
//};
using (var TDESAlgorithm = new TripleDESCryptoServiceProvider())
{
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
if (Message == null)
return "";
var DataToEncrypt = UTF8.GetBytes(Message);
try
{
var Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
return Convert.ToBase64String(Results);
}
private static string DoDecrypt(string Message)
{
// Decrypt string
byte[] Results;
var UTF8 = new UTF8Encoding();
using (var HashProvider = new MD5CryptoServiceProvider())
{
var TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(PassPhrase));
using (var TDESAlgorithm = new TripleDESCryptoServiceProvider())
{
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
//var DataToDecrypt = Convert.FromBase64String(Message);
var DataToDecrypt = new byte[0];
if (!IsBase64String(Message, out DataToDecrypt))
{
return Message;
}
try
{
var Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
return UTF8.GetString(Results);
}
public static bool IsBase64String(string base64String, out byte[] bytes)
{
bytes = null;
if (string.IsNullOrEmpty(base64String) || base64String.Length % 4 != 0
|| base64String.Contains(" ") || base64String.Contains("\t") || base64String.Contains("\r") || base64String.Contains("\n"))
return false;
try
{
bytes = Convert.FromBase64String(base64String);
return true;
}
catch (Exception)
{
// Handle the exception
}
return false;
}
public static string ASPEncrypter(string PriorValue, bool Decrypt)
{
// Public function to encrypt/decrypt string
if (String.IsNullOrWhiteSpace(PriorValue))
return "";
var Result = string.Empty;
if (Decrypt)
Result = DoDecrypt(PriorValue);
else
Result = DoEncrypt(PriorValue);
return Result;
}
I want encrypt in C# and decrypt in c++ but I have some Encoding problem :
example variables :
Key : gOtIPaLver—vS5UAnJbPqsDZSf,yJ1
IVString : gOtIPaLver—vS5
my c# code :
public static string EncryptString(string message, string KeyString, string IVString)
{
byte[] Key = UTF8Encoding.UTF8.GetBytes(KeyString.Substring(0,32));
byte[] IV = UTF8Encoding.UTF8.GetBytes(IVString);
string encrypted = null;
RijndaelManaged rj = new RijndaelManaged();
rj.Key = Key;
rj.IV = IV;
rj.Mode = CipherMode.CBC;
rj.Padding = PaddingMode.PKCS7;
try
{
MemoryStream ms = new MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, rj.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(message);
sw.Close();
}
cs.Close();
}
byte[] encoded = ms.ToArray();
encrypted = Convert.ToBase64String(encoded);
ms.Close();
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("A file error occurred: {0}", e.Message);
return null;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: {0}", e.Message);
}
finally
{
rj.Clear();
}
return encrypted;
}
When I try encrypt and my Key have some not ASCII char - count of bytes is more than lenght of string .
How Encoding I shound use ? In C++ I use EVP (default padding is PKCS7) .
static string decryptEX(string KS, string ctext)
{
EVP_CIPHER_CTX* ctx;
ctx = EVP_CIPHER_CTX_new();
string IV = KS.substr(0, 16);
int rc = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (byte*)&KS[0], (byte*)&IV[0]);
std::string rtext;
rtext.resize(ctext.size());
int out_len1 = (int)rtext.size();
rc = EVP_DecryptUpdate(ctx, (byte*)&rtext[0], &out_len1, (const byte*)&ctext[0], (int)ctext.size());
int out_len2 = (int)rtext.size() - out_len1;
rc = EVP_DecryptFinal_ex(ctx, (byte*)&rtext[0] + out_len1, &out_len2);
try
{
rtext.resize(out_len1 + out_len2);
}
catch (exception e)
{
}
return rtext;
}
Your call to
byte[] Key = UTF8Encoding.UTF8.GetBytes(KeyString.Substring(0,32));
fails because there are not 32 characters in that string. Yes, there would be 32 bytes if the string is encoded as UTF8. But Substring takes a count of characters.
Changing that line to
byte[] Key = UTF8Encoding.UTF8.GetBytes(KeyString);
gives a 32-byte long key.
Since you can't count on getting proper input for the KeyString, you could validate after this point that your key length is long enough.
byte[] Key = UTF8Encoding.UTF8.GetBytes(KeyString);
if (Key.Length < 32)
throw new KeyLengthException("some useful info as to why this was thrown"); // or some other appropriate Exception type you create or resuse.
If I'm correct in assuming which key, IV, and block sizes you require, this should do what you need:
public static string EncryptString(string message, string KeyString, string IVString)
{
byte[] Key = UTF8Encoding.UTF8.GetBytes(KeyString).Take(32).ToArray();
if (Key.Length < 32)
throw new Exception("KeyString not at least 32 bytes.");
byte[] IV = UTF8Encoding.UTF8.GetBytes(IVString).Take(16).ToArray();
if (Key.Length < 32)
throw new Exception("IVString not at least 16 bytes.");
string encrypted = null;
RijndaelManaged rj = new RijndaelManaged();
rj.KeySize = 128;
rj.BlockSize = 128;
rj.Key = Key;
rj.IV = IV;
rj.Mode = CipherMode.CBC;
rj.Padding = PaddingMode.PKCS7;
try
{
MemoryStream ms = new MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, rj.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(message);
sw.Close();
}
cs.Close();
}
byte[] encoded = ms.ToArray();
encrypted = Convert.ToBase64String(encoded);
ms.Close();
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("A file error occurred: {0}", e.Message);
return null;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: {0}", e.Message);
}
finally
{
rj.Clear();
}
return encrypted;
}
This question already has answers here:
Encrypting & Decrypting a String in C# [duplicate]
(7 answers)
Closed 6 years ago.
public string EncryptPwd(String strString)
{
int intAscii;
string strEncryPwd = "";
for (int intIndex = 0; intIndex < strString.ToString().Length; intIndex++)
{
intAscii = (int)char.Parse(strString.ToString().Substring(intIndex, 1));
intAscii = intAscii + 5;
strEncryPwd += (char)intAscii;
}
return strEncryPwd;
}
This is my code.Please suggest me it is right way or not.
you can use this code:
Encrypt string with password:
public static string EncryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToEncrypt = UTF8.GetBytes(Message);
try
{
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return Convert.ToBase64String(Results);
}
and Decrypt String with password:
public static string DecryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToDecrypt = Convert.FromBase64String(Message);
// Step 5. Bat dau giai ma chuoi
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
catch (Exception) { Results = DataToDecrypt; }
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return UTF8.GetString(Results);
}
Do you have a way to decrypt that? Here is another answer on SO
private static readonly UTF8Encoding Encoder = new UTF8Encoding();
public static string Encrypt(string unencrypted)
{
if (string.IsNullOrEmpty(unencrypted))
return string.Empty;
try
{
var encryptedBytes = MachineKey.Protect(Encoder.GetBytes(unencrypted));
if (encryptedBytes != null && encryptedBytes.Length > 0)
return HttpServerUtility.UrlTokenEncode(encryptedBytes);
}
catch (Exception)
{
return string.Empty;
}
return string.Empty;
}
public static string Decrypt(string encrypted)
{
if (string.IsNullOrEmpty(encrypted))
return string.Empty;
try
{
var bytes = HttpServerUtility.UrlTokenDecode(encrypted);
if (bytes != null && bytes.Length > 0)
{
var decryptedBytes = MachineKey.Unprotect(bytes);
if(decryptedBytes != null && decryptedBytes.Length > 0)
return Encoder.GetString(decryptedBytes);
}
}
catch (Exception)
{
return string.Empty;
}
return string.Empty;
}
I agree with all the previous answers (especially share pvv) but in case you really did want a Caesar Cipher (Caesar Cipher is a very weak encryption and should not be used in production), and if this is a learning exercise, then here is some code
string strString = "abcdefghijklmnopqrstuvwxyz";
string enc = String.Join("", strString.ToArray().Select(x =>(char)( 'a' + (x-'a'+5)%26)));
Console.WriteLine(enc);
Or using a for loop like you did
string strEncryPwd = "";
for (int index = 0; index < strString.ToString().Length; index++)
{
int plainChar = strString[index];
int encrypted = 'a' + (plainChar - 'a' + 5) % 26;
strEncryPwd += (char)encrypted;
}
Console.WriteLine(strEncryPwd);
I am trying to manually decrypt data which was encrypted with MachineKey.Protect(). I am using AES and SHA1 algoritms.
// unencrypted input in HEX: 010203
// AES key in HEX: CCA0DC9874B3F9E679E0A576F77EDF9B121CAB2F9A363A4EAF99976F7B51FA89
// want to decrypt this: A738E5F98920E37AB14C5F4332D4C7F0EC683680AAA0D34B806E75DECF04B7A3DB651E688B563F77BA107FB15990C88FB8023386
Here is an example.
// Some input data
var input = new byte[] { 1, 2, 3 };
// this just works fine
var protectedData = System.Web.Security.MachineKey.Protect(input, "ApplicationCookie", "v1");
// protectedData in hex: A738E5F98920E37AB14C5F4332D4C7F0EC683680AAA0D34B806E75DECF04B7A3DB651E688B563F77BA107FB15990C88FB8023386
// works
var unprotectedInput = System.Web.Security.MachineKey.Unprotect(protectedData, "ApplicationCookie", "v1");
// now lets do it manually
// in web.config machineKey is configured: AES and SHA1
var algorithm = new AesManaged();
algorithm.Padding = PaddingMode.PKCS7;
algorithm.Mode = CipherMode.CBC;
algorithm.KeySize = 256;
algorithm.BlockSize = 128;
var validationAlgorithm = new HMACSHA1();
// this is the key from web.config
var key = HexToBinary("CCA0DC9874B3F9E679E0A576F77EDF9B121CAB2F9A363A4EAF99976F7B51FA89");
using (SymmetricAlgorithm encryptionAlgorithm = algorithm)
{
encryptionAlgorithm.Key = key;
int offset = encryptionAlgorithm.BlockSize / 8; //16
int buffer1Count = validationAlgorithm.HashSize / 8; // 20
int count = checked(protectedData.Length - offset - buffer1Count); // 16
byte[] numArray = new byte[offset];
Buffer.BlockCopy((Array)protectedData, 0, (Array)numArray, 0, numArray.Length);
encryptionAlgorithm.IV = numArray; // in HEX: A738E5F98920E37AB14C5F4332D4C7F0
using (MemoryStream memoryStream = new MemoryStream())
{
using (ICryptoTransform decryptor = encryptionAlgorithm.CreateDecryptor())
{
using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(protectedData, offset, count);
// Padding is invalid and cannot be removed.
cryptoStream.FlushFinalBlock();
var result = memoryStream.ToArray();
}
}
}
}
I am getting an exception (padding is not right).
I do not know what else to try...
This is the code for MachineKey.Protect, https://msdn.microsoft.com/cs-cz/library/system.web.security.machinekey.protect(v=vs.110).aspx
public byte[] Protect(byte[] clearData)
{
// this is AESManaged
using (SymmetricAlgorithm encryptionAlgorithm = this._cryptoAlgorithmFactory.GetEncryptionAlgorithm())
{
// this is our key
encryptionAlgorithm.Key = this._encryptionKey.GetKeyMaterial();
if (this._predictableIV)
encryptionAlgorithm.IV = CryptoUtil.CreatePredictableIV(clearData, encryptionAlgorithm.BlockSize);
else
encryptionAlgorithm.GenerateIV();
byte[] iv = encryptionAlgorithm.IV;
using (MemoryStream memoryStream = new MemoryStream())
{
memoryStream.Write(iv, 0, iv.Length);
using (ICryptoTransform encryptor = encryptionAlgorithm.CreateEncryptor())
{
using (CryptoStream cryptoStream = new CryptoStream((Stream) memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(clearData, 0, clearData.Length);
cryptoStream.FlushFinalBlock();
using (KeyedHashAlgorithm validationAlgorithm = this._cryptoAlgorithmFactory.GetValidationAlgorithm())
{
validationAlgorithm.Key = this._validationKey.GetKeyMaterial();
byte[] hash = validationAlgorithm.ComputeHash(memoryStream.GetBuffer(), 0, checked ((int) memoryStream.Length));
memoryStream.Write(hash, 0, hash.Length);
return memoryStream.ToArray();
}
}
}
}
}
}
The decryption key is wrong.
MachineKey.Protect/UnProtect() modifies the key before using it.
It is doing something like this:
public static byte[] DeriveKey(byte[] key, int keySize, string primaryPurpose, params string[] specificPurposes)
{
var secureUtf8Encoding = new UTF8Encoding(false, true);
var hash = new HMACSHA512(key);
using (hash)
{
var label = secureUtf8Encoding.GetBytes(primaryPurpose);
byte[] context;
using (var memoryStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(memoryStream, secureUtf8Encoding))
{
foreach (var str in specificPurposes)
binaryWriter.Write(str);
context = memoryStream.ToArray();
}
}
return DeriveKeyImpl(hash, label, context, keySize);
}
}
public static byte[] DeriveKeyImpl(HMAC hmac, byte[] label, byte[] context, int keyLengthInBits)
{
int count1 = label != null ? label.Length : 0;
int count2 = context != null ? context.Length : 0;
byte[] buffer = new byte[checked(4 + count1 + 1 + count2 + 4)];
if (count1 != 0)
Buffer.BlockCopy((Array)label, 0, (Array)buffer, 4, count1);
if (count2 != 0)
Buffer.BlockCopy((Array)context, 0, (Array)buffer, checked(5 + count1), count2);
WriteUInt32ToByteArrayBigEndian(checked((uint)keyLengthInBits), buffer, checked(5 + count1 + count2));
int dstOffset = 0;
int val1 = keyLengthInBits / 8;
byte[] numArray = new byte[val1];
uint num = 1;
while (val1 > 0)
{
WriteUInt32ToByteArrayBigEndian(num, buffer, 0);
byte[] hash = hmac.ComputeHash(buffer);
int count3 = Math.Min(val1, hash.Length);
Buffer.BlockCopy((Array)hash, 0, (Array)numArray, dstOffset, count3);
checked { dstOffset += count3; }
checked { val1 -= count3; }
checked { ++num; }
}
return numArray;
}
It is very important to specify the right purpose. For standard MachineKey.Protect primary reason is "User.MachineKey.Protect". The key size for this example is 256 (in bits).
I've seen a few posts about this, but yet I can't seem to get this to work, any ideas?
RESULTS:
C# Encrypted string test = O6qzYiLPCpbXUf8PjMHpcg==
php Encrypted string test = SdS1dN1ugyAVYGFzHiTayg==
C# Code
public static string EncryptString(string message, string KeyString, string IVString)
{
byte[] Key = ASCIIEncoding.UTF8.GetBytes(KeyString);
byte[] IV = ASCIIEncoding.UTF8.GetBytes(IVString);
string encrypted = null;
RijndaelManaged rj = new RijndaelManaged();
rj.Key = Key;
rj.IV = IV;
rj.Mode = CipherMode.CBC;
try
{
MemoryStream ms = new MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, rj.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(message);
sw.Close();
}
cs.Close();
}
byte[] encoded = ms.ToArray();
encrypted = Convert.ToBase64String(encoded);
ms.Close();
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("A file error occurred: {0}", e.Message);
return null;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: {0}", e.Message);
}
finally
{
rj.Clear();
}
return encrypted;
}
string enctext = EncryptString("test", "qwertyuiopasdfghjklzxcvbnmqwerty", _"1234567890123456");
PHP
function aesenc($message, $keystring, $ivstring){
$IV_UTF = mb_convert_encoding($ivstring, 'UTF-8');
$KEY_UTF = mb_convert_encoding($keystring, 'UTF-8');
return base64_encode( mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $KEY_UTF, $message, MCRYPT_MODE_CBC, $IV_UTF));
}
$enctext = aesenc("test", "qwertyuiopasdfghjklzxcvbnmqwerty", _"1234567890123456");
Found the answer, needed to add padding to the $message in php
function aesenc($message, $keystring, $ivstring){
$IV_UTF = mb_convert_encoding($ivstring, 'UTF-8');
$KEY_UTF = $keystring;
return base64_encode( mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $KEY_UTF, addpadding($message), MCRYPT_MODE_CBC, $IV_UTF));
}
function addpadding($string, $blocksize = 16)
{
$len = strlen($string);
$pad = $blocksize - ($len % $blocksize);
$string .= str_repeat(chr($pad), $pad);
return $string;
}