Home > Java > javaTutorial > Detailed example of des encryption and decryption between Java and asp.net

Detailed example of des encryption and decryption between Java and asp.net

黄舟
Release: 2017-09-06 10:05:22
Original
1682 people have browsed it

Recently there is a new project made in Java. The old project is asp.net. The interface transmission requires DES encryption and decryption. I checked some information online and found that most of them cannot be used immediately. I debugged and processed it myself. The specific code As follows:

The key must be 8 digits


        /// <summary>   
        /// 利用DES加密算法加密字符串(可解密)   
        /// </summary>   
        /// <param name="pToEncrypt">被加密的字符串</param>   
        /// <param name="key">密钥(只支持8个字节的密钥)</param>   
        /// <returns>加密后的字符串</returns>   
        public static string DESEnCode(string pToEncrypt, string key)
        {
            try
            {
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
                provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
                byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(pToEncrypt);
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
                stream2.Write(bytes, 0, bytes.Length);
                stream2.FlushFinalBlock();
                StringBuilder builder = new StringBuilder();
                foreach (byte num in stream.ToArray())
                {
                    builder.AppendFormat("{0:X2}", num);
                }
                stream.Close();
                return builder.ToString();
            }
            catch (Exception) { return "xxxx"; }
        }
         /// <summary>   
        /// 解密  
        /// </summary>   
        /// <param name="plaintext">加密后的字符串</param>   
        /// <param name="key">密钥(只支持8个字节的密钥)</param>   
        /// <returns>解密后的字符串</returns>   
        public static string Decode(string str, string key, string encLangue)
        {
            try
            {
                //str=Ruijie.Pcfg.Utils.DESEncrypt.HexTostring(str);
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
                provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
                byte[] buffer = new byte[str.Length / 2];
                for (int i = 0; i < (str.Length / 2); i++)
                {
                    int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
                    buffer[i] = (byte)num2;
                }
                
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
                stream2.Write(buffer, 0, buffer.Length);
                stream2.FlushFinalBlock();
                stream.Close();
                if (encLangue == "java")
                {
                    return Encoding.GetEncoding("utf-8").GetString(stream.ToArray());
                }
                else
                {
                    return Encoding.GetEncoding("gb2312").GetString(stream.ToArray());
                }
                
            }
            catch (Exception) { return ""; }
        }
Copy after login

The corresponding java method is as follows:

package com.testspring;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class DesHelper {
/**
    * 加密
    *
    *
    * **/
   public String encrypt(String message,String key)
   {
       return toHexString(encryptByte(message,key)).toUpperCase();
   }
   /**
    * 明文加密后的数组
    *
    *
    * **/
   public byte[] encryptByte(String message, String key) {
       byte[] s={};
       try
       {
           Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
           DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
           SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
           SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
           IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
           cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
           return cipher.doFinal(message.getBytes("UTF-8"));
       }
       catch (Exception ex) {
}
       return s;
   }
   /**
    * 数组转化成16进制
    *
    *
    * **/
   public static String toHexString(byte b[]) {
       StringBuffer hexString = new StringBuffer();
       for (int i = 0; i < b.length; i++) {
           String plainText = Integer.toHexString(0xff & b[i]);
           if (plainText.length() < 2)
               plainText = "0" + plainText;
           hexString.append(plainText);
       }
       return hexString.toString();
   }
   /**
    * 解密
    *ciphertext 加密字符串,key 密钥,encLangue 加密语言
    *
    * **/
   public String decrypt(String ciphertext, String key,String encLangue) {
       try {
           byte[] bytesrc = convertHexString(ciphertext);
           Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
           DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
           SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
           SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
           IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
           cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
           byte[] retByte = cipher.doFinal(bytesrc);
           if(encLangue=="java")
           {
               return new String(retByte,"utf-8");
           }
           else
           {
               return new String(retByte);
           }
       }
       catch (Exception ex)
       {
}
       return "";
   }
   /**
    * 转化16进制字符串为byte数组
    *
    * **/
   public static byte[] convertHexString(String ss) {
       byte digest[] = new byte[ss.length() / 2];
       for (int i = 0; i < digest.length; i++) {
           String byteString = ss.substring(2 * i, 2 * i + 2);
           int byteValue = Integer.parseInt(byteString, 16);
           digest[i] = (byte) byteValue;
       }
       return digest;
   }
}
Copy after login

The above is the detailed content of Detailed example of des encryption and decryption between Java and asp.net. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template