2021-02-23

java~和.net相通的DES-ECB加解密技术

起因

首先,对于一个公司,即有.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的几个不同

  1. byte类型对于.net是(0255),而java来说它是有符号的,是(-128127)
  2. 对于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个字节。









原文转载:http://www.shaoqun.com/a/581577.html

跨境电商:https://www.ikjzd.com/

marks spencer:https://www.ikjzd.com/w/2385

国际标准书号:https://www.ikjzd.com/w/174


起因首先,对于一个公司,即有.net又有java开发来说,加解密是需要相互打通的,因为,根据莫非定律你迟早会有".net加密让java解密"的情况。.net实现publicstaticstringEncrypt(SymmetricAlgorithmalgorithm,stringplaintext,stringkey){TripleDESCryptoServiceProvidertripleDes
蜜芽宝贝官网:https://www.ikjzd.com/w/1320
环球b2b:https://www.ikjzd.com/w/1762
inkfrog:https://www.ikjzd.com/w/668
不雅视频21秒?都是整容惹的祸:http://lady.shaoqun.com/m/a/47564.html
店小秘:https://www.ikjzd.com/w/1531
2019年终亚马逊卖家分布图鉴!亚马逊活跃卖家数量最多的竟是......:https://www.ikjzd.com/home/112123

No comments:

Post a Comment