可通用的VB.NET、C#与Java的Des加解密代码
1、Java版
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | import java.io.UnsupportedEncodingException; import java.security.SecureRandom; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.IvParameterSpec; import Decoder.BASE64Decoder; import Decoder.BASE64Encoder; import javax.crypto.SecretKeyFactory; import javax.crypto.SecretKey; import javax.crypto.Cipher; public class MyDesc { 	   public MyDesc() {} 	    //测试 	    public static void main(String args[]) throws UnsupportedEncodingException { 	     //待加密内容 	     String str = "{\"pid\":\"511025198710264794\",\"pname\":false}"; 	     //密码,长度要是8的倍数 	     String password = "2018052400018841"; 	     String result = MyDesc.encrypt(str.getBytes("UTF-8"),password); 	     System.out.println("加密后:"+result);  //uMI2SuMFepPhQxytg/ONQPwfCnlLZHYOQiuIY6u176gbgHCw8nD7u3fMV7IgSr5o 	     //直接将如上内容解密 	     try {	    	 	             String decryResult = MyDesc.decrypt(result, password); 	             System.out.println("解密后:"+decryResult);  //{"pid":"511025198710264794","pname":false} 	     } catch (Exception e1) { 	             e1.printStackTrace(); 	     } 	 } 	   /** 	    * 加密 	    * @param datasource 	    * @param password 	    * @return 	    */ 	    public static String encrypt(byte[] datasource, String password) {  	    	String strIv = "12345678"; 	        try{ 	        SecureRandom random = new SecureRandom(); 	        DESKeySpec desKey = new DESKeySpec(password.getBytes("UTF-8")); 	        //创建一个密匙工厂,然后用它把DESKeySpec转换成 	        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); 	        SecretKey securekey = keyFactory.generateSecret(desKey); 	        //Cipher对象实际完成加密操作 	        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); 	        //用密匙初始化Cipher对象 	        IvParameterSpec param = new IvParameterSpec(strIv.getBytes()); 	        cipher.init(Cipher.ENCRYPT_MODE, securekey, param); 	        //现在,获取数据并加密 	        //正式执行加密操作 	        byte[] buf =  cipher.doFinal(datasource); 	        String utf8 = new BASE64Encoder().encodeBuffer(buf); 	        return utf8; 	        }catch(Throwable e){ 	                e.printStackTrace(); 	        } 	        return null; 	} 	   /** 	    * 解密 	    * @param src 	    * @param password 	    * @return 	    * @throws Exception 	    */ 	    public static String decrypt(String src, String password) throws Exception { 	    	String strIv = "12345678"; 	    	// DES算法要求有一个可信任的随机数源 	            SecureRandom random = new SecureRandom(); 	            // 创建一个DESKeySpec对象 	            DESKeySpec desKey = new DESKeySpec(password.getBytes()); 	            // 创建一个密匙工厂 	            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); 	            // 将DESKeySpec对象转换成SecretKey对象 	            SecretKey securekey = keyFactory.generateSecret(desKey); 	            // Cipher对象实际完成解密操作 	            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); 	            // 用密匙初始化Cipher对象 	            IvParameterSpec param = new IvParameterSpec(strIv.getBytes());     	            cipher.init(Cipher.DECRYPT_MODE, securekey, param); 	            // 真正开始解密操作 	            byte[] dec = new BASE64Decoder().decodeBuffer(src); 	            byte[] utf8 = cipher.doFinal(dec); 	            String decryptedStr = new String(utf8, "UTF-8"); 	            return decryptedStr;	 	        } } | 
2、C#版
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | using System; using System.Collections.Generic; using System.Linq; using System; using System.Linq; using System.Web.Script.Serialization; using System.Runtime.Serialization; using System.Dynamic; using System.Net; using System.IO; using System.Collections.Specialized; using System.Web; using System.Security.Cryptography; using System.Text; namespace testDESC {     static class Test     {         /// <summary>         /// 解密         /// </summary>         /// <param name="encryptedString"></param>         /// <param name="keyString"></param>         /// <returns></returns>         public static string Decrypt(string encryptedString, string keyString)         {             keyString = keyString.Substring(0, 8);             byte[] btKey = Encoding.UTF8.GetBytes(keyString);             byte[] btIv = Encoding.UTF8.GetBytes("12345678");             var des = new DESCryptoServiceProvider();             des.Mode = CipherMode.CBC;//这里指定加密模式为CBC             des.Padding = PaddingMode.PKCS7;             des.Key = btKey;             des.IV = btIv;             using (var ms = new MemoryStream())             {                 try                 {                     byte[] inData = Convert.FromBase64String(encryptedString);                     using (var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))                     {                         cs.Write(inData, 0, inData.Length);                         cs.FlushFinalBlock();                     }                     return Encoding.UTF8.GetString(ms.ToArray());                 }                 catch (Exception ex)                 {                     return "-1";                     // throw ex;                 }             }         }         /// <summary>         /// 加密         /// </summary>         /// <param name="sourceString"></param>         /// <param name="keyString"></param>         /// <returns></returns>         public static string Encrypt(string sourceString, string keyString)         {             keyString = keyString.Substring(0, 8);             byte[] btIv = Encoding.UTF8.GetBytes("12345678");             byte[] btKey = Encoding.UTF8.GetBytes(keyString);             try             {                 DESCryptoServiceProvider des = new DESCryptoServiceProvider();                 using (MemoryStream ms = new MemoryStream())                 {                     byte[] inData = Encoding.UTF8.GetBytes(sourceString);                     using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIv), CryptoStreamMode.Write))                     {                         cs.Write(inData, 0, inData.Length);                         cs.FlushFinalBlock();                     }                     return Convert.ToBase64String(ms.ToArray());                 }             }             catch             {                 return "-1";             }         }         static void Main(string[] args)         {             string str = "{\"pid\":\"511025198710264794\",\"pname\":false}";             string re = Encrypt(str, "2018052400018841");             Console.WriteLine("加密:" + re); //uMI2SuMFepPhQxytg/ONQPwfCnlLZHYOQiuIY6u176gbgHCw8nD7u3fMV7IgSr5o             string re1 = Decrypt(re, "2018052400018841");             Console.WriteLine("解密:" + re1); //{"pid":"511025198710264794","pname":false}         }     } } | 
3、VB.NET版
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | Imports System.IO Imports System.Security.Cryptography Imports System.Text ''' <summary> ''' DES加密 ''' </summary> Public Class DES     ''' <summary>     ''' 进行DES加密     ''' </summary>     ''' <param name="pToEncrypt">需要加密的字符串</param>     ''' <param name="sKey">密钥</param>     ''' <returns></returns>     Public Function Encrypt(ByVal pToEncrypt As String, ByVal sKey As String) As String         Using des As DESCryptoServiceProvider = New DESCryptoServiceProvider()             Dim inputByteArray As Byte() = Encoding.UTF8.GetBytes(pToEncrypt)             des.Key = Encoding.UTF8.GetBytes(sKey)             des.IV = Encoding.UTF8.GetBytes("12345678")             des.Padding = PaddingMode.PKCS7             des.Mode = CipherMode.ECB             Dim ms As MemoryStream = New MemoryStream()             Try                 Using cs As CryptoStream = New CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)                     cs.Write(inputByteArray, 0, inputByteArray.Length)                     cs.FlushFinalBlock()                     cs.Close()                 End Using                 Dim base64 As String = Convert.ToBase64String(ms.ToArray())                 Return base64             Catch ex As Exception                 Return "-1"             Finally                 ms.Close()             End Try         End Using     End Function     ''' <summary>     ''' 进行DES解密     ''' </summary>     ''' <param name="pToDecrypt">需要解密的字符串</param>     ''' <param name="sKey">密钥</param>     ''' <returns></returns>     Public Function Decrypt(ByVal pToDecrypt As String, ByVal sKey As String) As String         Dim inputByteArray As Byte() = Convert.FromBase64String(pToDecrypt)         Using des As DESCryptoServiceProvider = New DESCryptoServiceProvider()             des.Key = Encoding.UTF8.GetBytes(sKey)             des.IV = Encoding.UTF8.GetBytes("12345678")             des.Padding = PaddingMode.PKCS7             des.Mode = CipherMode.ECB             Dim ms As MemoryStream = New MemoryStream()             Try                 Using cs As CryptoStream = New CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)                     cs.Write(inputByteArray, 0, inputByteArray.Length)                     cs.FlushFinalBlock()                     cs.Close()                 End Using                 Dim str As String = Encoding.UTF8.GetString(ms.ToArray())                 Return str             Catch ex As Exception                 Return "-1"             Finally                 ms.Close()             End Try         End Using     End Function End Class Public Class Form1     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click         Dim myDES As New DES         Debug.Print(myDES.Decrypt("vqzlic2Xtm1pWb4GwaH0Mdh4SETUnomlkKfyxfxF2RUI4J1O4SIWcw==", "ZMCCXZQA"))     End Sub     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click         Dim myDES As New DES         Debug.Print(myDES.Encrypt("{""username"":""张三"",""sex"":""男""}", "ZMCCXZQA"))     End Sub End Class | 
可通用的C...
