我正在使用PHP加密我的数据:
$encrypted_string = mcrypt_encrypt(MCRYPT_DES, 'abcdefgh' , $input, MCRYPT_MODE_CBC, 'qwerasdf' );
$encrypted_string = base64_encode($encrypted_string);
return $encrypted_string;
并在C#中解密相同内容:
public string Decrypt(string input)
{
input = Server.UrlDecode(input);
byte[] binary = Convert.FromBase64String(input);
input = Encoding.GetEncoding(28591).GetString(binary);
DES tripleDes = DES.Create();
tripleDes.IV = Encoding.ASCII.GetBytes("NAVEEDNA");
tripleDes.Key = Encoding.ASCII.GetBytes("abcdegef");
tripleDes.Mode = CipherMode.CBC;
tripleDes.Padding = PaddingMode.Zeros;
ICryptoTransform crypto = tripleDes.CreateDecryptor();
byte[] decodedInput = Decoder(input);
byte[] decryptedBytes = crypto.TransformFinalBlock(decodedInput, 0, decodedInput.Length);
return Encoding.ASCII.GetString(decryptedBytes);
}
public byte[] Decoder(string input)
{
byte[] bytes = new byte[input.Length / 2];
int targetPosition = 0;
for (int sourcePosition = 0; sourcePosition < input.Length; sourcePosition += 2)
{
string hexCode = input.Substring(sourcePosition, 2);
bytes[targetPosition++] = Byte.Parse(hexCode, NumberStyles.AllowHexSpecifier);
}
return bytes;
}
当我尝试在C#中解密字符串时,它会抛出以下异常:
输入字符串的格式不正确。
在以下行: Byte.Parse(hexCode,NumberStyles.AllowHexSpecifier);
知道我该怎么做错了吗?
答案 0 :(得分:1)
尝试Byte.Parse(hexCode, System.Globalization.NumberStyles.HexNumber);
由于AllowHexSpecifier用于0x1b样式的十六进制数字。