键盘人生

After all,tomorrow is another day

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

通过这个方法可以实现java和C#相互加密与解密 并能保持解密出来一致


方法一:通过.NET的key和VI来生成对应于java的key

java:

   

Java代码  收藏代码
  1. <span style="color: #888888;">import java.security.Key;  
  2. import java.security.spec.AlgorithmParameterSpec;  
  3.   
  4. import javax.crypto.Cipher;  
  5. import javax.crypto.SecretKeyFactory;  
  6. import javax.crypto.spec.DESKeySpec;  
  7. import javax.crypto.spec.IvParameterSpec;  
  8.   
  9. import sun.misc.BASE64Decoder;  
  10. import sun.misc.BASE64Encoder;  
  11.   
  12. public class CryptoTools {  
  13.   
  14.     private static final byte[] DESkey = { (byte0x15, (byte0xE7,  
  15.             (byte0xA1, (byte0x22, (byte0x96, (byte0x8B, (byte0x24,  
  16.             (byte0xFA };// 设置密钥,略去  
  17.   
  18.     private static final byte[] DESIV = { (byte0xCE, (byte0x35, (byte0x5,  
  19.             (byte0xD, (byte0x98, (byte0x91, (byte0x8, (byte0xA };// 设置向量,略去  
  20.   
  21.     static AlgorithmParameterSpec iv = null;// 加密算法的参数接口,IvParameterSpec是它的一个实现  
  22.     private static Key key = null;  
  23.   
  24.     public CryptoTools() throws Exception {  
  25.         DESKeySpec keySpec = new DESKeySpec(DESkey);// 设置密钥参数  
  26.         iv = new IvParameterSpec(DESIV);// 设置向量  
  27.         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂  
  28.         key = keyFactory.generateSecret(keySpec);// 得到密钥对象  
  29.   
  30.     }  
  31.   
  32.     public String encode(String data) throws Exception {  
  33.         Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher  
  34.         enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式,给出密钥和向量  
  35.         byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));  
  36.         BASE64Encoder base64Encoder = new BASE64Encoder();  
  37.         return base64Encoder.encode(pasByte);  
  38.     }  
  39.   
  40.     public String decode(String data) throws Exception {  
  41.         Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");  
  42.         deCipher.init(Cipher.DECRYPT_MODE, key, iv);  
  43.         BASE64Decoder base64Decoder = new BASE64Decoder();  
  44.         byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data));  
  45.         return new String(pasByte, "UTF-8");  
  46.     }  
  47.   
  48.     public static void main(String[] args) throws Exception {  
  49.   
  50.         CryptoTools tools = new CryptoTools();  
  51.         System.out.println("加密:" + tools.encode("天下"));  
  52.         System.out.println("解密:" + tools.decode(tools.encode("天下")));  
  53.     }  
  54.   
  55. }</span>  

 



×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××




方法二:通过java的key来生成对应于.NET的key和VI

C#:

C#代码  收藏代码
  1. <span style="color: #888888;">using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8.   
  9.     
  10. using System.Configuration;     
  11. using System.Web;     
  12. using System.Security.Cryptography;     
  13. using System.IO;     
  14.     
  15.   
  16. namespace DES  
  17. {  
  18.     public partial class Form1 : Form  
  19.     {  
  20.         public Form1()  
  21.         {  
  22.             InitializeComponent();  
  23.         }  
  24.   
  25.         private void button1_Click(object sender, EventArgs e)  
  26.         {  
  27.             string jiami = textBox1.Text;  
  28.            textBox2.Text= DESEnCode(jiami, "11111111");  
  29.         }  
  30.   
  31.           public static string DES_Key = "11111111";    
  32.   
  33.     #region DESEnCode DES加密     
  34.     public static string DESEnCode(string pToEncrypt, string sKey)     
  35.     {  
  36.        // string pToEncrypt1 = HttpContext.Current.Server.UrlEncode(pToEncrypt);     
  37.         DESCryptoServiceProvider des = new DESCryptoServiceProvider();  
  38.         byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);     
  39.     
  40.         //建立加密对象的密钥和偏移量      
  41.         //原文使用ASCIIEncoding.ASCII方法的GetBytes方法      
  42.         //使得输入密码必须输入英文文本      
  43.         des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);     
  44.         des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);     
  45.         MemoryStream ms = new MemoryStream();     
  46.         CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);     
  47.     
  48.         cs.Write(inputByteArray, 0, inputByteArray.Length);     
  49.         cs.FlushFinalBlock();     
  50.     
  51.         StringBuilder ret = new StringBuilder();     
  52.         foreach (byte b in ms.ToArray())     
  53.         {     
  54.             ret.AppendFormat("{0:X2}", b);     
  55.         }     
  56.         ret.ToString();     
  57.         return ret.ToString();     
  58.     }    
  59.     #endregion    
  60.   
  61.     #region DESDeCode DES解密     
  62.     public static string DESDeCode(string pToDecrypt, string sKey)     
  63.     {     
  64.         //    HttpContext.Current.Response.Write(pToDecrypt + "<br>" + sKey);     
  65.         //    HttpContext.Current.Response.End();     
  66.         DESCryptoServiceProvider des = new DESCryptoServiceProvider();     
  67.     
  68.         byte[] inputByteArray = new byte[pToDecrypt.Length / 2];     
  69.         for (int x = 0; x < pToDecrypt.Length / 2; x++)     
  70.         {     
  71.             int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));     
  72.             inputByteArray[x] = (byte)i;     
  73.         }     
  74.     
  75.         des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);     
  76.         des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);     
  77.        MemoryStream ms = new MemoryStream();     
  78.         CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);     
  79.         cs.Write(inputByteArray, 0, inputByteArray.Length);     
  80.         cs.FlushFinalBlock();     
  81.     
  82.         StringBuilder ret = new StringBuilder();     
  83.     
  84.        // return HttpContext.Current.Server.UrlDecode(System.Text.Encoding.Default.GetString(ms.ToArray()));  
  85.         return System.Text.Encoding.Default.GetString(ms.ToArray());    
  86.     }    
  87.     #endregion     
  88.   
  89.     private void button2_Click(object sender, EventArgs e)  
  90.     {  
  91.         string jiemi = textBox2.Text;  
  92.         textBox3.Text = DESDeCode(jiemi,"11111111");  
  93.     }  
  94.     
  95.     
  96.     }  
  97. }  
  98. </span>  

 




java:

   

Java代码  收藏代码
  1. <span style="color: #888888;">import javax.crypto.Cipher;     
  2. import javax.crypto.SecretKey;     
  3. import javax.crypto.SecretKeyFactory;     
  4. import javax.crypto.spec.DESKeySpec;     
  5. import javax.crypto.spec.IvParameterSpec;     
  6.     
  7.     
  8. public class Des {     
  9.     private byte[] desKey;     
  10.     
  11.          
  12.     //解密数据     
  13.     public static String decrypt(String message,String key) throws Exception {     
  14.               
  15.             byte[] bytesrc =convertHexString(message);        
  16.             Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");         
  17.             DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));        
  18.             SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");        
  19.             SecretKey secretKey = keyFactory.generateSecret(desKeySpec);        
  20.             IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));     
  21.                      
  22.             cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);           
  23.                
  24.             byte[] retByte = cipher.doFinal(bytesrc);          
  25.             return new String(retByte);      
  26.     }     
  27.     
  28.     public static byte[] encrypt(String message, String key)     
  29.             throws Exception {     
  30.         Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");     
  31.     
  32.         DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));     
  33.     
  34.         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");     
  35.         SecretKey secretKey = keyFactory.generateSecret(desKeySpec);     
  36.         IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));     
  37.         cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);     
  38.     
  39.         return cipher.doFinal(message.getBytes("UTF-8"));     
  40.     }     
  41.          
  42.     public static byte[] convertHexString(String ss)      
  43.     {      
  44.     byte digest[] = new byte[ss.length() / 2];      
  45.     for(int i = 0; i < digest.length; i++)      
  46.     {      
  47.     String byteString = ss.substring(2 * i, 2 * i + 2);      
  48.     int byteValue = Integer.parseInt(byteString, 16);      
  49.     digest[i] = (byte)byteValue;      
  50.     }      
  51.     
  52.     return digest;      
  53.     }      
  54.     
  55.     
  56.     public static void main(String[] args) throws Exception {     
  57.         String key = "11111111";     
  58.         String value="aa";     
  59.         String jiami=java.net.URLEncoder.encode(value, "utf-8").toLowerCase();     
  60.              
  61.         System.out.println("加密数据:"+jiami);     
  62.         String a=toHexString(encrypt(jiami, key)).toUpperCase();     
  63.              
  64.          
  65.         System.out.println("加密后的数据为:"+a);     
  66.         String b=java.net.URLDecoder.decode(decrypt(a,key), "utf-8") ;     
  67.         System.out.println("解密后的数据:"+b);     
  68.     
  69.     }     
  70.     
  71.          
  72.     public static String toHexString(byte b[]) {     
  73.         StringBuffer hexString = new StringBuffer();     
  74.         for (int i = 0; i < b.length; i++) {     
  75.             String plainText = Integer.toHexString(0xff & b[i]);     
  76.             if (plainText.length() < 2)     
  77.                 plainText = "0" + plainText;     
  78.             hexString.append(plainText);     
  79.         }     
  80.              
  81.         return hexString.toString();     
  82.     }     
  83.     
  84. }    
  85. </span>  

 


 

posted on 2011-03-30 17:12  Dr.Wang  阅读(6211)  评论(0编辑  收藏  举报