起因
首先,对于一个公司,即有.net又有java开发来说,加解密是需要相互打通的,因为,根据莫非定律你迟早会有“.net加密让java解密“的情况。
.net实现
public static string Encrypt(SymmetricAlgorithm algorithm, string plaintext, string key) { TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider(); MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider(); algorithm.Key = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key)); algorithm.Mode = CipherMode.ECB; Console.WriteLine("IV=" + Convert.ToBase64String(algorithm.IV)); ICryptoTransform transformer = algorithm.CreateEncryptor(); byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(plaintext); byte[] result = transformer.TransformFinalBlock(Buffer, 0, Buffer.Length); return Convert.ToBase64String(result); }
.net和java的几个不同
- byte类型对于.net是(0255),而java来说它是有符号的,是(-128127)
- 对于DES来说,默认的java支持的密钥是8字节,而.net里algorithm.Key是16个字节,所以用原生Java的des是不能和.net互通的
java实现
需要第三方包bcprov-jdk15on
<dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.64&l.........