MD5值转换(Hex 32位 <-> base64 24位)
关于MD5值的原理本文不在介绍,本文主要介绍MD5值的两种编码的相互转换(32位和BASE64编码的24位),实际应用过程中经常会涉及到两种编码的相互转换。快熟使用工具tomeko.net。
C#示例程序:
using System;
using System.Text;
namespace test
{
class Program
{
static void Main(string[] args)
{
string original = "123456";
Console.WriteLine("original: " + original);
var md5Hex = BitConverter.ToString(new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(original))).Replace("-", "").ToLower();
Console.WriteLine("md5Hex: " + md5Hex);
//b64是以=结尾的长度为24位的密文
var b64 = Convert.ToBase64String(new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(original)));
Console.WriteLine("b64: " + b64);
//b64Tomd5Hex
var b64Tomd5Hex = BitConverter.ToString(new System.Security.Cryptography.FromBase64Transform().TransformFinalBlock(Encoding.Default.GetBytes(b64), 0, Encoding.Default.GetBytes(b64).Length)).Replace("-", "").ToLower();
Console.WriteLine("b64Tomd5Hex: " + b64Tomd5Hex);
//md5HexToBase64
string md5HexToBase64 = HexString2B64String(md5Hex);
Console.WriteLine("md5HexToBase64: " + md5HexToBase64);
Console.ReadKey(true);
}
/// <summary>
/// 32位md5转24位base64
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string HexString2B64String(string input)
{
return Convert.ToBase64String(HexStringToHex(input));
}
public static byte[] HexStringToHex(string inputHex)
{
var resultantArray = new byte[inputHex.Length / 2];
for (var i = 0; i < resultantArray.Length; i++)
{
resultantArray[i] = Convert.ToByte(inputHex.Substring(i * 2, 2), 16);
}
return resultantArray;
}
}
}
测试结果:
original: 123456
md5Hex: e10adc3949ba59abbe56e057f20f883e
b64: 4QrcOUm6Wau+VuBX8g+IPg==
b64Tomd5Hex: e10adc3949ba59abbe56e057f20f883e
md5HexToBase64: 4QrcOUm6Wau+VuBX8g+IPg==