发布于2021-03-10 18:24 阅读(869) 评论(0) 点赞(19) 收藏(5)
首先,对于一个公司,即有.net又有java开发来说,加解密是需要相互打通的,因为,根据莫非定律你迟早会有“.net加密让java解密“的情况。
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);
}
需要第三方包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个字节。
原文链接:https://www.cnblogs.com/lori/p/14437994.html
作者:天天在家
链接:http://www.javaheidong.com/blog/article/112381/2a747efb696a09f95c37/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!