Can anyone please let me know where I made a mistake in this code? This code is written in C#.NET. I need to write an algorithm for encoding a string using base64 format using C#.NET, and then decoded with base64_decode() using PHP. Please see the snippit below:
System.Security.Cryptography.RijndaelManaged rijndaelCipher = new System.Security.Cryptography.RijndaelManaged();
rijndaelCipher.Mode = System.Security.Cryptography.CipherMode.CBC;
rijndaelCipher.Padding = System.Security.Cryptography.PaddingMode.Zeros;
rijndaelCipher.KeySize = 256;
rijndaelCipher.BlockSize = 128;
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(_key);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;
System.Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
System.Security.Cryptography.ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(unencryptedString);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherBytes);
I think your code sample is doing "encryption", and you want "encoding".
For encoding a string with Based64 in C#, it should look like this:
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
And the PHP should look like this:
<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?>
I need to write an algorithm for encoding a string using base64 format using C#.net
That's actually quite easy. You don't need all that cryptography stuff that your copy-and-pasted code is using. The following suffices:
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
string outputString = Convert.ToBase64String(bytes);
If you plan to send the data from C# to PHP via a HTTP GET request, don't forget to UrlEncode it. See this question for details:
C# to PHP base64 encode/decode
Related
In PHP i do following steps:
<?php
$key="mM8Y28b5R7KFe3Y5";
$data="298052380sbEUREinzellizenz Spieler SEN329739test120211572380R-00001003authorization19";
$hash=hash_hmac("sha384", $data, $key);
echo $hash;
?>
i get following output:
f34fb28f6462cde18a92ee854d289ba5aed3cfc07d0abb52cfef3b70028e1b38b098ae17514a9121d43d3d6f684eccd8
I try to do this in .NET with:
string data = "298052380sbEUREinzellizenz Spieler SEN329739test120211572380R-00001003authorization19";
string key = "mM8Y28b5R7KFe3Y5";
string hash = "";
using (SHA384 sha384Hash = SHA384.Create())
{
byte[] sourceBytes = Encoding.ASCII.GetBytes(data);
byte[] hashBytes = sha384Hash.ComputeHash(sourceBytes);
hash = BitConverter.ToString(hashBytes).Replace("-", String.Empty).ToLower();
}
and i get
77b7eccd4f66b07c66e2c49b83e53bf84dfd4dc67ec60007df4476adfe16d9b0bfdd6e58e9a5008bde4908335d161ef5
i tried also:
var keyByte = Encoding.ASCII.GetBytes(key);
using (HMACSHA256 sha384Hash = new HMACSHA256(keyByte))
{
byte[] sourceBytes = Encoding.ASCII.GetBytes(data);
byte[] hashBytes = sha384Hash.ComputeHash(sourceBytes);
hash2 = BitConverter.ToString(hashBytes).Replace("-", String.Empty).ToLower();
}
hash2 is
ceaabe254e19d77940ac3edfdf2fa3d1de424d569136e8deb770aa81be5cb24a
i don't get the difference. I checked already the Encodings, but i see no differents.
What i am doing wrong?
use the second example but with
using (HMACSHA384 sha384Hash = new HMACSHA384(Encoding.ASCII.GetBytes(key)))
I am trying to decrypt a blowfish encrypted string with Bouncycastle in C#.
I am able to easily encrypt and decrypt my own string but, unfortunately, I have to decrypt a string that is generated by another system.
I AM able to recreate that same string with C# / Bouncycastle using the following but I have yet to decrypt it successfully.
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
...
static readonly Encoding Encoding = Encoding.UTF8;
public string BlowfishEncrypt(string strValue, string key)
{
try
{
BlowfishEngine engine = new BlowfishEngine();
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
KeyParameter keyBytes = new KeyParameter(Encoding.GetBytes(key));
cipher.Init(true, keyBytes);
byte[] inB = Encoding.GetBytes(strValue);
byte[] outB = new byte[cipher.GetOutputSize(inB.Length)];
int len1 = cipher.ProcessBytes(inB, 0, inB.Length, outB, 0);
cipher.DoFinal(outB, len1);
return BitConverter.ToString(outB).Replace("-", "");
}
catch (Exception)
{
return "";
}
}
Below is what I have for decryption at the moment. The line that fails with error "pad block corrupted" is cipher.DoFinal(out2, len2);
public string BlowfishDecrypt(string name, string keyString)
{
BlowfishEngine engine = new BlowfishEngine();
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
StringBuilder result = new StringBuilder();
cipher.Init(false, new KeyParameter(Encoding.GetBytes(keyString)));
byte[] out1 = Convert.FromBase64String(name);
byte[] out2 = new byte[cipher.GetOutputSize(out1.Length)];
int len2 = cipher.ProcessBytes(out1, 0, out1.Length, out2, 0);
cipher.DoFinal(out2, len2); //Pad block corrupted error happens here
String s2 = BitConverter.ToString(out2);
for (int i = 0; i < s2.Length; i++) {
char c = s2[i];
if (c != 0) {
result.Append(c.ToString());
}
}
return result.ToString();
}
Any idea what I might be doing wrong in BlowfishDecrypt()?
Note:
I converted the above (encrypt and decrypt) from a bouncycastle Java example I found somewhere; the encrypt works. The only difference I can see is that the Java example uses a StringBuffer where I use a StringBuilder.
Thank you, Artjom B!
byte[] out1 = Convert.FromBase64String(name);
Should have been
byte[] out1 = Hex.Decode(name);
From there, all I had to do was convert the Hex to a string.
I have been given a set of codes from a third party that need encrypting/decrypting however the sample encryption code they gave me was in C# and I am primarily a front-end PHP developer.
I have set-up a slimmed down working example of the code I was provided
here using the sample key of A818163DD5E0DE87.
public static byte[] HexStringToByteArray(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;
}
// Convers a byte array to a HEX string
public static string ByteArrayToHexString(byte[] bytes)
{
StringBuilder hexString = new StringBuilder(bytes.Length * 2);
for (int i = 0; i < bytes.Length; i++)
{
hexString.Append(bytes[i].ToString("X2"));
}
return hexString.ToString();
}
public static byte[] Encrypt()
{
string plainText = "GROW06BP";
DESCryptoServiceProvider desCrypto = new DESCryptoServiceProvider();
desCrypto.Key = HexStringToByteArray("A818163DD5E0DE87");
desCrypto.IV = HexStringToByteArray("A818163DD5E0DE87");
desCrypto.Mode = CipherMode.CBC;
desCrypto.Padding = PaddingMode.Zeros;
// Create a buffer for the Plain Text using ASCIIEncoding
byte[] plaintextBytes = (new ASCIIEncoding()).GetBytes(plainText);
// Create a memory stream for the encrypted bytes
MemoryStream msEncrypt = new MemoryStream();
// Create a CryptoStream using the memory stream and the passed Algorithm
CryptoStream csEncrypt = new CryptoStream(msEncrypt, desCrypto.CreateEncryptor(), CryptoStreamMode.Write);
// Write the plaintext to the CryptoStream
csEncrypt.Write(plaintextBytes, 0, plaintextBytes.Length);
// Close the CryptoStream
csEncrypt.Close();
// Read the Encrypted bytes into our buffer
byte[] encryptedTextBytes = msEncrypt.ToArray();
// Close the Memory Stream
msEncrypt.Close();
// And return the encrypted buffer
return encryptedTextBytes;
}
I have scoured stack overflow and other sites in an attempt to replicate this in PHP but nothing comes close to the correct output. I'm also confused by which cipher I am meant to be using and how to convert the key and iv to match the C# example. Below is what I have attempted so far.
$key = unpack('H*', "A818163DD5E0DE87");
$key = "A818163DD5E0DE87";
$iv = $key;
$plaintext = "GROW06BP";
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext,MCRYPT_MODE_CBC, $iv);
echo base64_encode($ciphertext);
Any help would be appreciated.
Things you need to consider:
DESCryptoServiceProvider -> mcrypt_module_open('des'
desCrypto.Mode = CipherMode.CBC; -> mcrypt_module_open(...,..., 'cbc',
key,iv and the cipher output are "treated" with HexStringToByteArray(), pack('H*) can undo that
So, given the output of the .net fiddle (7860D97E56DA6A40) that leads to
<?php
$msgHex = '7860D97E56DA6A40';
$keyHex = 'A818163DD5E0DE87';
$ivHex = 'A818163DD5E0DE87'; // really? invalidates the use-case of an iv :-/
// this reverts the effect of HexStringToByteArray()
$msg = pack('H*', $msgHex);
$key = pack('H*', $keyHex);
$iv = pack('H*', $ivHex);
// add error handing !
$module = mcrypt_module_open('des', '', 'cbc', '');
mcrypt_generic_init($module, $key, $iv);
$plaintext = mdecrypt_generic($module, $msg);
mcrypt_generic_deinit($module);
echo $plaintext;
output: GROW06BP
As I've already mentioned in my comment, you're using the wrong algorithm in your PHP code since it's Rijndael. What you should use is MCRYPT_DES.
$key = "A818163DD5E0DE87";
// Here you need pack instead of unpack
$packKey = pack("H*",$key);
// you should use the key as the initialization vector
// use something like mcrypt_create_iv to generate an IV
$iv = $packKey;
$plaintext = "GROW06BP";
// replaced MCRYPT_RIJNDAEL_128 with MCRYPT_DES
$ciphertext = mcrypt_encrypt(MCRYPT_DES, $packKey, $plaintext,MCRYPT_MODE_CBC, $iv);
echo base64_encode($ciphertext);
This will produce the same output as the C# code
Can anyone please let me know where I made a mistake in this code? This code is written in C#.NET. I need to write an algorithm for encoding a string using base64 format using C#.NET, and then decoded with base64_decode() using PHP. Please see the snippit below:
System.Security.Cryptography.RijndaelManaged rijndaelCipher = new System.Security.Cryptography.RijndaelManaged();
rijndaelCipher.Mode = System.Security.Cryptography.CipherMode.CBC;
rijndaelCipher.Padding = System.Security.Cryptography.PaddingMode.Zeros;
rijndaelCipher.KeySize = 256;
rijndaelCipher.BlockSize = 128;
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(_key);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;
System.Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
System.Security.Cryptography.ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(unencryptedString);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherBytes);
I think your code sample is doing "encryption", and you want "encoding".
For encoding a string with Based64 in C#, it should look like this:
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
And the PHP should look like this:
<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?>
I need to write an algorithm for encoding a string using base64 format using C#.net
That's actually quite easy. You don't need all that cryptography stuff that your copy-and-pasted code is using. The following suffices:
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
string outputString = Convert.ToBase64String(bytes);
If you plan to send the data from C# to PHP via a HTTP GET request, don't forget to UrlEncode it. See this question for details:
C# to PHP base64 encode/decode
I've got this php code and I'd like to get the exact equivalent C#
$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_192, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
$encryptedData = mcrypt_encrypt(MCRYPT_RIJNDAEL_192, $key, $salt . $message . $nonce, MCRYPT_MODE_CBC, $iv);
$base64Data = base64_encode($salt . $iv . $encryptedData);
$urlEncodedData = rawurlencode($base64Data);
All contributions gratefully received!
Too many variables to convert directly; I recommend that you examine what it does and rewrite it in C# to adhere to the intent of the original code.
Nay sayers and doom mongers, behold!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Web;
namespace EncryptData
{
class EncryptData
{
private static readonly Encoding ASCII_ENCODING = new System.Text.ASCIIEncoding();
private static string md5(string text)
{
return BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(ASCII_ENCODING.GetBytes(text))).Replace("-", "").ToLower();
}
public abstract string nonce();
public abstract string salt();
public readonly string EncryptedData;
public EncryptData(string message)
{
// set up encrytion object
RijndaelManaged aes192 = new RijndaelManaged();
aes192.KeySize = 192;
aes192.BlockSize = 192;
aes192.Padding = PaddingMode.None;
aes192.Mode = CipherMode.CBC;
aes192.Key = ASCII_ENCODING.GetBytes(md5(SECRET_KEY));
aes192.GenerateIV();
string localSalt = salt();
string localNonce = nonce();
// form the string for encrypting
// and put into byte array
string textToEncrypt = localSalt + message+ localNonce;
byte[] plainTextBytes = ASCII_ENCODING.GetBytes(textToEncrypt);
// encrypt the data
ICryptoTransform encryptor = aes192.CreateEncryptor();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
cs.Write(plainTextBytes, 0, plainTextBytes.Length);
// convert our encrypted data from a memory stream into a byte array.
byte[] cypherTextBytes = ms.ToArray();
// close memory stream
ms.Close();
byte[] combined = null;
// combine data and convert to byte array
combined = CombinedData(localSalt, aes192.IV, cypherTextBytes);
// url encode data once converted to base64 string
EncryptedData = HttpUtility.UrlEncode(base64CombinedData(combined), ASCII_ENCODING);
}
public byte[] CombinedData(string salt, byte[] IV, byte[] cypherTextBytes)
{
// convert salt string into byte array
byte[] saltBytes = ASCII_ENCODING.GetBytes(salt);
// catenate all the byte arrays into one
// set up dest byte array with required size
byte[] rv = new byte[saltBytes.Length + IV.Length + cypherTextBytes.Length];
// copy in each byte array
Buffer.BlockCopy(saltBytes, 0, rv, 0, saltBytes.Length);
Buffer.BlockCopy(IV, 0, rv, saltBytes.Length, IV.Length);
Buffer.BlockCopy(cypherTextBytes, 0, rv, saltBytes.Length + IV.Length, cypherTextBytes.Length);
return rv;
}
public string base64CombinedData(byte[] rv)
{
return Convert.ToBase64String(rv);
}
}
}
Sorry, but to be honest - the question is rather silly.
All this code does is some nasty crypting and encoding.
PHP is full of global functions from modules that do the thing.
For C# You need to find proper libs/classes that have methods for crypting etc. It will probably ahve different logic and parameters.
I bet You'll even get some output differences due to different implementations.
I suppose this is the closest thing You'll find to an answer to Your question
In the example provided by Rob I think he should have used PaddingMode.Zero instead of PaddingMode.None, as this is the way mcrypt_encrypt() adds paddings.