1. 程式人生 > >MD5+DES在C#.NET與Java/Android中的加解密使用

MD5+DES在C#.NET與Java/Android中的加解密使用

main 模式 NPU ++ 代碼 加密、解密 ets 推薦 lock

一、背景
後臺(C#.NET)使用一個MD5+DES的加解密算法,查了下,很多網友都使用了這個算法。在Android裏,也需要這個算法,如何把這個加解密算法切換成Java版,成了難題。畢竟好久沒涉及到這一塊了,只知道:

MD5(Message-Digest Algorithm 5,信息-摘要算法5):是一種信息摘要算法、哈希算法,不可逆;
DES(Data Encryption Standard,數據加密標準):是一種對稱加密算法,加解密需要同一個密鑰;
AES(Advanced Encryption Standard,高級加密標準), 也是一種對稱加密算法,是DES的升級版。

目前來說,DES比較脆弱,所以推薦用AES。

核心算法都是一樣的,各種語言都封裝好了,就是如何使用的問題。為了弄懂C#中的代碼,竟然把11G多的VS2017也給安裝了(在線編譯工具無法編譯通過,最後在VS中改了才可以,推薦:http://ideone.com/)。經過一番折騰,終於切換成功。

二、C#源碼
從網上把解密的算法也一起復制過來研究

#region ========加密========
/// <summary>
/// 加密
/// </summary>
/// <param name="Text"></param>
/// <returns></returns>
public static string Encrypt(string Text)
{
return Encrypt(Text, "Ralap");
}

/// <summary>
/// 加密數據
/// </summary>
/// <param name="Text"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string Encrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray;
inputByteArray = Encoding.Default.GetBytes(Text);
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
return ret.ToString();
}

#endregion


#region ========解密========


/// <summary>
/// 解密
/// </summary>
/// <param name="Text"></param>
/// <returns></returns>
public static string Decrypt(string Text)
{
return Decrypt(Text, "Ralap");
}
/// <summary>
/// 解密數據
/// </summary>
/// <param name="Text"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string Decrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
int len;
len = Text.Length / 2;
byte[] inputByteArray = new byte[len];
int x, i;
for (x = 0; x < len; x++)
{
i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Encoding.Default.GetString(ms.ToArray());
}

#endregion

三、C#源碼分析及替換MD5加密類
把這段代碼復制過來,並不能使用,因為System.Web.Security報錯。不會整,就想著換掉個方式,最後使用MD5CryptoServiceProvider類來替換,成功復原結果。如下:

using System;
using System.Text;
using System.Security.Cryptography;

namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string key = "Ralap";
Console.WriteLine("==========加密=========");
string secret = Encrypt("Android, 你好!", key);
Console.WriteLine("result of Encrypt=" + secret);
Console.WriteLine("==========解密=========");
string data = Decrypt(secret, key);
Console.WriteLine("result of Decrypt=" + data);
Console.ReadKey();
}

#region ========加密========
public static string Encrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray;
inputByteArray = Encoding.UTF8.GetBytes(Text);

string md5 = Md5Hash(sKey).Substring(0, 8);
Console.WriteLine("md5=" + md5);

des.Key = ASCIIEncoding.ASCII.GetBytes(md5);
des.IV = ASCIIEncoding.ASCII.GetBytes(md5);
Console.WriteLine("Key=" + Bytes2Hex(des.Key));

System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();

return Bytes2Hex(ms.ToArray());
}

public static string Decrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
int len;
len = Text.Length / 2;
byte[] inputByteArray = new byte[len];
int x, i;
for (x = 0; x < len; x++)
{
i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
inputByteArray[x] = (byte)i;
}

string md5 = Md5Hash(sKey).Substring(0, 8);

des.Key = ASCIIEncoding.ASCII.GetBytes(md5);
des.IV = ASCIIEncoding.ASCII.GetBytes(md5);
Console.WriteLine("Key=" + Bytes2Hex(des.Key));

System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Encoding.UTF8.GetString(ms.ToArray());
}

private static string Md5Hash(string input)
{
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
return Bytes2Hex(data);
}

private static string Bytes2Hex(byte[] bytes) {
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
sBuilder.Append(bytes[i].ToString("X2"));
}
return sBuilder.ToString();
}

#endregion
}
}

運行結果如下:


註意:

網上的Md5Hash()結果並沒有轉換成大寫,所以掉坑了。
因為這裏使用到了中文,所以並沒有使用Default默認編碼,而使用UTF-8編碼:Encoding.UTF8.GetBytes()和Encoding.UTF8.GetString()
. 另外,Md5Hash()的另一種寫法:
public static string Md5Hash(string input)
{
MD5 md5Hash = MD5.Create();
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
return Bytes2Hex(data);
}

四、Java版
對著C#,先獲取key的MD5前8位,使用它作為key和iv,進行DES加解密。有坑的地方就是要全部轉換成大寫字母。其它沒什麽好說的,直接上代碼和運行結果就一目了然:

package com.example;

import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
* File Name : EncryptClass
* Description :
* Author : Ralap
* Create Date : 2017/3/19
* Version : v1
*/
public class EncryptClass {

public static void main(String[] args) {
println("=========Java版=========");
String key = "Ralap";
println("=========加密=========");
String secret = encrypt("Android, 你好!", key);
println("result of encrypt=%s", secret);
println("========解密==========");
String data = decrypt(secret, key);
println("result of decrypt=%s", data);
}

/**
* 加密
*
* @param data 要加密的數據
* @param key 密鑰
*/
private static String encrypt(String data, String key) {
try {
// 獲取key的MD5值
byte[] md5Bytes = MessageDigest.getInstance("MD5").digest(key.getBytes());

// md5值轉換成十六進制(大寫)
String md5 = bytes2Hex(md5Bytes).toUpperCase();
println("keyMD5=%s", md5);

// 並獲取前8位作為真實的key
String pwd = md5.substring(0, 8);
println("pwd=%s", pwd);

// 使用DES 加密,key和iv都使用pwd
// 根據pwd,生成DES加密後的密鑰,SecretKeySpec對象
SecretKeySpec secretKey = new SecretKeySpec(pwd.getBytes(), "DES");

// 根據pwd,創建一個初始化向量IvParameterSpec對象
IvParameterSpec iv = new IvParameterSpec(pwd.getBytes());

// 創建密碼器,參數:算法/模式/填充
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
// 用key和iv初始化密碼器,參1:opmode,操作模式-加密、解密等。
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

// 執行(加密)並返回結果(字節數組)
byte[] resultBytes = cipher.doFinal(data.getBytes(""UTF-8""));

// 轉換成十六進制(大寫)
return bytes2Hex(resultBytes).toUpperCase();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 解密
*
* @param data 要解密的數據
* @param key 密鑰
*/
private static String decrypt(String data, String key) {
try {
// 把加密的十六進制字符串數據轉換成字節數組
int len = data.length() >> 1;
byte[] dataBytes = new byte[len];
for (int i=0; i<len; i++) {
int index = i << 1;
dataBytes[i] = (byte)Integer.parseInt(data.substring(index, index + 2), 16);
}

// 獲取key的MD5值
byte[] md5Bytes = MessageDigest.getInstance("MD5").digest(key.getBytes());
String pwd = bytes2Hex(md5Bytes).toUpperCase().substring(0, 8);

// 創建key和iv
SecretKeySpec secretKey = new SecretKeySpec(pwd.getBytes(), "DES");
IvParameterSpec iv = new IvParameterSpec(pwd.getBytes());

// DES 解密
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] resultBytes = cipher.doFinal(dataBytes);

return new String(resultBytes, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 字節數組轉換成十六進制字符串
*/
private static String bytes2Hex(byte[] bytes) {
if (bytes == null) {
return null;
}
StringBuilder resultSB = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() < 2) {
resultSB.append("0");
}
resultSB.append(hex);
}
return resultSB.toString();
}

private static void println(String format, Object... args) {
System.out.println(String.format(format, args));
}
}

運行結果:


說明:
1、創建密鑰的一行代碼:

SecretKeySpec secretKey = new SecretKeySpec(pwd.getBytes(), "DES");

也可以用這三行來創建:

DESKeySpec keySpec = new DESKeySpec(pwd.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
Key secretKey = keyFactory.generateSecret(keySpec);

2、服務器與客戶端編碼格式一定要一致,特別是原始數據含中文的情況

MD5+DES在C#.NET與Java/Android中的加解密使用