For investors
股价:
5.36 美元 %For investors
股价:
5.36 美元 %认真做教育 专心促就业
首先,对于一个公司,即有.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 /version>
scope compile /scope>
/dependency
实现与.net互通的加密过程
private static final String ALGORITHM = "DESede";
private static final String CIPHER_TRANSFER = "DESede/ECB/PKCS5Padding";
private static final String ENCODING = "UTF-8";
static {
init();
}
public static void init() {
BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
Security.addProvider(bouncyCastleProvider);
}
/**
* 初始化key.
*
* @param key
*/
@SneakyThrows
static SecretKey getSecretKey(String key) {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] bkeys = md5.digest(key.getBytes());
SecretKey secretKey = new SecretKeySpec(bkeys, ALGORITHM);
return secretKey;
}
/**
* 字符串加密.
*
* @param plainText
* @param key
* @return
* @throws Exception
*/
@SneakyThrows
public static String encryptToBase64(String plainText, String key) {
SecretKey secretKey = getSecretKey(key);
Cipher cipher = Cipher.getInstance(CIPHER_TRANSFER);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] result = cipher.doFinal(plainText.getBytes(ENCODING));
String s1 = Base64.encodeBase64String(result);
return s1;
}
上面代码,主要是对于key的生成要注意,使用了与.net相同的md5对原始key进行的加密,保存它是16个字节。