public static String byteArr2HexStr(byte[] bytIn) { StringBuilder builder = new StringBuilder(); foreach (byte num in bytIn) { builder.AppendFormat("{0:X2}", num); } return builder.ToString();// byteArr2HexStr(encrypt(padStr(strIn).getBytes())); } public static byte[] encrypt(string str, string key) { DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); provider.Mode = System.Security.Cryptography.CipherMode.ECB; provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8)); provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8)); byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(str); MemoryStream stream = new MemoryStream(); CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write); stream2.Write(bytes, 0, bytes.Length); return stream.ToArray(); } public static String padStr(String sourceData) { byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(sourceData); int n = (8 - (bytes.Length) % 8); if (n > 0 && n != 8) { for (int i = 0; i < n; i++) sourceData = sourceData + " "; } return sourceData; } /// <summary> /// 加密算法-适用于java解密,不足8的倍数已补足空格 /// </summary> /// <param name="Text"></param> /// <param name="sKey"></param> /// <returns></returns> public static string Encrypt(string Text, string sKey) { return byteArr2HexStr(encrypt(padStr(Text), sKey)); }
调用:
Encrypt("待加密字符串","密钥");