一个离开.NET的程序员

ryhan

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

java加解密:

 1 public class Encrypt
 2 {
 3     public Encrypt()
 4     {
 5     }
 6     public static String eCode(String needEncrypt)  throws Exception
 7     {
 8         byte result[] = null;
 9         try
10         {
11             Cipher enCipher = Cipher.getInstance("DES");
12             javax.crypto.SecretKey key = Key.loadKey();
13             enCipher.init(1, key);
14             result = enCipher.doFinal(needEncrypt.getBytes());
15             BASE64Encoder b = new BASE64Encoder();
16             ByteArrayOutputStream bos = new ByteArrayOutputStream();
17             b.encode(result, bos);
18             result = bos.toByteArray();
19         }
20         catch(Exception e)
21         {
22             throw e;
23         }
24         return new String(result);
25     }
26     public static String dCode(byte result[])
27         throws Exception
28     {
29         String s = null;
30         String key = "";
31         try
32         {
33          Cipher deCipher = Cipher.getInstance("DES");
34             deCipher.init(2, Key.loadKey());
35             BASE64Decoder d = new BASE64Decoder();
36             result = d.decodeBuffer(new String(result));
37             byte[] iv = deCipher.getIV();
38             byte strByte[] = deCipher.doFinal(result);
39             s = new String(strByte);
40         }
41         catch(Exception e)
42         {
43             throw e;
44         }
45         return s;
46     }
47 }
注:Key.loadKey()实现从配置文件中读取key,然后base64解码,封装在SecretKey对象中。

原:http://blog.sina.com.cn/s/blog_6d51d25e0100lp28.html

.Net解密:

(详见:http://www.cnblogs.com/ryhan/archive/2012/08/28/2660372.html)

 1 private string dCode(string str,string strKey)
 2   {
 3    byte[] bStr = Convert.FromBase64String(str);
 4    byte[] key  = Convert.FromBase64String(strKey);
 5    DES des = new DESCryptoServiceProvider();
 6    des.Mode = System.Security.Cryptography.CipherMode.ECB;
 7    des.Key = key;
 8    des.IV = new byte[8];
 9    byte[] resultBytes = des.CreateDecryptor().TransformFinalBlock(bStr, 0, bStr.Length);
10    return System.Text.Encoding.UTF8.GetString(resultBytes);
11   }
12  
 算法区别:
 1.java和.net默认的加密模式不同,java是ECB模式,.net是CBC模式。如果.net不手工指定ECB模式的话,在bStr.length>8时会抛异常。
 2.java和.net默认初始化向量(IV)不同,java中如不指定IV,则自动以byte[8]初始化,而.net会抛异常,要des.IV = new byte[8];
posted on 2012-08-28 16:14  ryhan  阅读(605)  评论(0编辑  收藏  举报