zoukankan      html  css  js  c++  java
  • C#与Java同步加密解密DES算法

    在实际项目中,往往前端和后端使用不同的语言。比如使用C#开发客户端,使用Java开发服务器端。有时出于安全性考虑需要将字符加密传输后,由服务器解密获取。本文介绍一种采用DES算法的C#与Java同步加密解密的代码。

    C#端代码:(注意:DES的秘钥采用8位字符)

    [csharp] view plain copy
     
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Globalization;  
    6. using System.Threading.Tasks;  
    7. using System.Security.Cryptography;  
    8. using System.IO;  
    9.   
    10. namespace ChatDemo.util  
    11. {  
    12.     public static class PasswordHelper  
    13.     {  
    14.         ///<summary><![CDATA[字符串DES加密函数]]></summary>    
    15.         ///<param name="str"><![CDATA[被加密字符串 ]]></param>    
    16.         ///<param name="key"><![CDATA[密钥 ]]></param>     
    17.         ///<returns><![CDATA[加密后字符串]]></returns>       
    18.         public static string EncodeDES(string str, string key)  
    19.         {  
    20.             try  
    21.             {  
    22.                 DESCryptoServiceProvider provider = new DESCryptoServiceProvider();  
    23.                 provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));  
    24.                 provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));  
    25.                 byte[] bytes = Encoding.GetEncoding("UTF-8").GetBytes(str);  
    26.                 MemoryStream stream = new MemoryStream();  
    27.                 CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);  
    28.                 stream2.Write(bytes, 0, bytes.Length);  
    29.                 stream2.FlushFinalBlock();  
    30.                 StringBuilder builder = new StringBuilder();  
    31.                 foreach (byte num in stream.ToArray())  
    32.                 {  
    33.                     builder.AppendFormat("{0:X2}", num);  
    34.                 }  
    35.                 stream.Close();  
    36.                 return builder.ToString();  
    37.             }  
    38.             catch (Exception) { return "xxxx"; }  
    39.         }  
    40.         ///<summary><![CDATA[字符串DES解密函数]]></summary>    
    41.         ///<param name="str"><![CDATA[被解密字符串 ]]></param>    
    42.         ///<param name="key"><![CDATA[密钥 ]]></param>     
    43.         ///<returns><![CDATA[解密后字符串]]></returns>       
    44.         public static string DecodeDES(string str, string key)  
    45.         {  
    46.             try  
    47.             {  
    48.                 DESCryptoServiceProvider provider = new DESCryptoServiceProvider();  
    49.                 provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));  
    50.                 provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));  
    51.                 byte[] buffer = new byte[str.Length / 2];  
    52.                 for (int i = 0; i < (str.Length / 2); i++)  
    53.                 {  
    54.                     int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);  
    55.                     buffer[i] = (byte)num2;  
    56.                 }  
    57.                 MemoryStream stream = new MemoryStream();  
    58.                 CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);  
    59.                 stream2.Write(buffer, 0, buffer.Length);  
    60.                 stream2.FlushFinalBlock();  
    61.                 stream.Close();  
    62.                 return Encoding.GetEncoding("UTF-8").GetString(stream.ToArray());  
    63.             }  
    64.             catch (Exception) { return ""; }  
    65.         }  
    66.     }  
    67. }  

    Java端代码:

    [java] view plain copy
     
    1. package com.hbcloudwide.didaoa.chatserver.util;  
    2.   
    3.   
    4. import javax.crypto.Cipher;  
    5. import javax.crypto.SecretKey;  
    6. import javax.crypto.SecretKeyFactory;  
    7. import javax.crypto.spec.DESKeySpec;  
    8. import javax.crypto.spec.IvParameterSpec;  
    9.   
    10. import org.apache.commons.codec.digest.DigestUtils;  
    11.   
    12. /** 
    13.  * 密码加密解密处理工具类 
    14.  *  
    15.  * @author lee 
    16.  * 
    17.  */  
    18. public class PasswordUtil {  
    19.   
    20.     // 解密数据  
    21.     /** 
    22.      * DES解密 
    23.      * @param message 
    24.      * @param key 
    25.      * @return 
    26.      * @throws Exception 
    27.      * 
    28.      * lee on 2016-12-26 00:28:18 
    29.      */  
    30.     public static String DecodeDES(String message, String key) throws Exception {  
    31.   
    32.         byte[] bytesrc = convertHexString(message);  
    33.         Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");  
    34.         DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));  
    35.         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
    36.         SecretKey secretKey = keyFactory.generateSecret(desKeySpec);  
    37.         IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));  
    38.         cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);  
    39.         byte[] retByte = cipher.doFinal(bytesrc);  
    40.         return new String(retByte);  
    41.     }  
    42.   
    43.     /** 
    44.      * DES加密 
    45.      * @param message 
    46.      * @param key 
    47.      * @return 
    48.      * @throws Exception 
    49.      * 
    50.      * lee on 2016-12-26 00:28:28 
    51.      */  
    52.     public static byte[] EncodeDES(String message, String key) throws Exception {  
    53.         Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");  
    54.         DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));  
    55.         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
    56.         SecretKey secretKey = keyFactory.generateSecret(desKeySpec);  
    57.         IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));  
    58.         cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);  
    59.         return cipher.doFinal(message.getBytes("UTF-8"));  
    60.     }  
    61.       
    62.     /** 
    63.      * MD5加密 
    64.      * 使用org.apache.commons.codec.digest.DigestUtils加密 
    65.      * http://commons.apache.org/proper/commons-codec/download_codec.cgi 
    66.      * @param message 
    67.      * @return 
    68.      *  
    69.      * lee on 2016-12-26 00:28:28     
    70.          */  
    71.     public static String EncodeMD5(String message) {          
    72.         return DigestUtils.md5Hex(message);  
    73.     }  
    74.   
    75.   
    76.     public static byte[] convertHexString(String ss) {  
    77.         byte digest[] = new byte[ss.length() / 2];  
    78.         for (int i = 0; i < digest.length; i++) {  
    79.             String byteString = ss.substring(2 * i, 2 * i + 2);  
    80.             int byteValue = Integer.parseInt(byteString, 16);  
    81.             digest[i] = (byte) byteValue;  
    82.         }  
    83.         return digest;  
    84.     }  
    85.   
    86.     public static String toHexString(byte b[]) {  
    87.         StringBuffer hexString = new StringBuffer();  
    88.         for (int i = 0; i < b.length; i++) {  
    89.             String plainText = Integer.toHexString(0xff & b[i]);  
    90.             if (plainText.length() < 2)  
    91.                 plainText = "0" + plainText;  
    92.             hexString.append(plainText);  
    93.         }  
    94.         return hexString.toString();  
    95.     }  
    96.       
    97.       
    98. }  

    C# DES加密后的字符传递到Java端获取后,可以正确进行解密。反之亦然。
    BTW:Java代码中有一个方法用来进行MD5加密,采用org.apache.commons.codec.digest.DigestUtils进行加密。

  • 相关阅读:
    AndroidStudio中提示:android.content.res.Resources NotFoundException: String resource ID 0x
    Android中使用Room(ORM关系映射框架)对sqllite数据库进行增删改查
    Android中怎样使用Navicat可视化查看sqllite的数据库(查看db文件)
    Android中怎样在工具类中获取Context对象
    AndroidStudio中提示:This project uses AndroidX dependencies, but the ‘android.useAndroidX‘ property is not enabled
    AndroidStudio中Attatch debugger to Android Ptocess时 Choose Process后OK是灰色的
    AndroidStudio中调试时提示waiting for debugger的奇葩解决
    Java中使用Gson解析泛型类型数据
    vscode怎么快速创建生成html模板
    IntelliJ IDEA + Tomcat ;On Upate Action 与 On Frame Deactivation
  • 原文地址:https://www.cnblogs.com/amylis_chen/p/8679117.html
Copyright © 2011-2022 走看看