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

原由

首先,對於一個公司,即有.net又有java開發來講,加解密是須要相互打通的,由於,根據莫非定律你早晚會有「.net加密讓java解密「的狀況。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-jdk15onide

<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個字節。.net

相關文章
相關標籤/搜索