c#加密对称JAVA--DES/RSA/成功解密成功。

c#加密对称java DES

 

 

 

找过好多资料和下载过好多文件,对称加密就是解不出来,JAVA和.NET的系统类库里都有封装DES对称加密的实现方式却各不相同,甚至有时会让自己难以解决其中的问题,比如JAVA加密后的结果在.NET中解密不出来等,最近项目有跨JAVA和.NET的加解密,经过不断的调试,终于让它们可以互相加密解密了。

过程就不说了

调试记录:

方法一:使用java加密和c#加密对比,老是差几位对不上,JAVA无法解析

 

秘钥:DESTEST0

示例一:

秘钥:DESTEST0

字符串:123456

【JAVA解密】
ClVgIaLATSY=

【C#解密】:
ClVgIaLATSY=

【结果】:一致

两者解密结果正确

你也为这样就结束了吗? no no no,小伙子你还太年轻

示例二:
内容
{"sex":"男","username":"张三"}
【JAVA解密】
postStr:{"sex":"男","username":"张三"}
dtNza+iraz7dWIbZRskINjrQ7gj0OKstHHjwmlp60e0cioA3VGhJfw==

【C#解密】:
dtNza+iraz7HqdqNjYkMTpGo9aRG7VzETlIgBbXi5A33d+LLvFSqBQ==

【结果】:不一致

我的娘呀,找找找原因

 

找了半天原因:终于找到原因:

  // java 默认的是ECB模式,PKCS5padding;c#默认的CBC模式,PKCS7padding 所以这里我们默认使用ECB方式

所以你一直按各种示例,各种调试就是玩,解密不一样

经过不断的尝试的JAVA人员查看,终于调试通,做个备注和分享。

 成功的DES加解密

一、调试成功,上代码

C#调试成功代码

 1 public class DESHelper
 2    {
 3  
 4        /// <summary>
 5        /// DES加密算法
 6        /// </summary>
 7        /// <param name="encryptString">要加密的字符串</param>
 8        /// <param name="sKey">加密码Key</param>
 9        /// <returns>正确返回加密后的结果,错误返回源字符串</returns>
10        public static string ToDESEncrypt(string encryptString, string sKey)
11        {
12            try
13            {
14  
15                byte[] keyBytes = Encoding.UTF8.GetBytes(sKey);
16                byte[] keyIV = keyBytes;
17                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
18  
19                DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
20  
21                // java 默认的是ECB模式,PKCS5padding;c#默认的CBC模式,PKCS7padding 所以这里我们默认使用ECB方式
22                desProvider.Mode = CipherMode.ECB;
23                MemoryStream memStream = new MemoryStream();
24                CryptoStream crypStream = new CryptoStream(memStream, desProvider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
25  
26                crypStream.Write(inputByteArray, 0, inputByteArray.Length);
27                crypStream.FlushFinalBlock();
28                return Convert.ToBase64String(memStream.ToArray());
29  
30            }
31            catch
32            {
33                return encryptString;
34            }
35        }
36  
37  
38        /// <summary>
39        /// DES解密算法
40        /// </summary>
41        /// <param name="decryptString">要解密的字符串</param>
42        /// <param name="sKey">加密Key</param>
43        /// <returns>正确返回加密后的结果,错误返回源字符串</returns>
44        public static string ToDESDecrypt(string decryptString, string sKey)
45        {
46            byte[] keyBytes = Encoding.UTF8.GetBytes(sKey);
47            byte[] keyIV = keyBytes;
48            byte[] inputByteArray = Convert.FromBase64String(decryptString);
49  
50            DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
51  
52            // java 默认的是ECB模式,PKCS5padding;c#默认的CBC模式,PKCS7padding 所以这里我们默认使用ECB方式
53            desProvider.Mode = CipherMode.ECB;
54            MemoryStream memStream = new MemoryStream();
55            CryptoStream crypStream = new CryptoStream(memStream, desProvider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
56  
57            crypStream.Write(inputByteArray, 0, inputByteArray.Length);
58            crypStream.FlushFinalBlock();
59            return Encoding.Default.GetString(memStream.ToArray());
60  
61        }
62    }

 

JAVA

 1 public class DESHelper {
 2  
 3     private byte[] desKey;
 4  
 5     public DES(String desKey) {
 6         this.desKey = desKey.getBytes();
 7     }
 8  
 9     public byte[] desEncrypt(byte[] plainText) throws Exception {
10         SecureRandom sr = new SecureRandom();
11         byte rawKeyData[] = desKey;
12         DESKeySpec dks = new DESKeySpec(rawKeyData);
13         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
14         SecretKey key = keyFactory.generateSecret(dks);
15         Cipher cipher = Cipher.getInstance("DES");
16         cipher.init(Cipher.ENCRYPT_MODE, key, sr);
17         byte data[] = plainText;
18         byte encryptedData[] = cipher.doFinal(data);
19         return encryptedData;
20     }
21  
22     public byte[] desDecrypt(byte[] encryptText) throws Exception {
23         SecureRandom sr = new SecureRandom();
24         byte rawKeyData[] = desKey;
25         DESKeySpec dks = new DESKeySpec(rawKeyData);
26         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
27         SecretKey key = keyFactory.generateSecret(dks);
28         Cipher cipher = Cipher.getInstance("DES");
29         cipher.init(Cipher.DECRYPT_MODE, key, sr);
30         byte encryptedData[] = encryptText;
31         byte decryptedData[] = cipher.doFinal(encryptedData);
32         return decryptedData;
33     }
34  
35     public String encrypt(String input) throws Exception {
36         return base64Encode(desEncrypt(input.getBytes()));
37     }
38  
39     public String decrypt(String input) throws Exception {
40         byte[] result = base64Decode(input);
41         return new String(desDecrypt(result));
42     }
43  
44     public static String base64Encode(byte[] s) {
45         if (s == null)
46             return null;
47         BASE64Encoder b = new sun.misc.BASE64Encoder();
48         return b.encode(s);
49     }
50  
51     public static byte[] base64Decode(String s) throws IOException {
52         if (s == null)
53             return null;
54         BASE64Decoder decoder = new BASE64Decoder();
55         byte[] b = decoder.decodeBuffer(s);
56         return b;
57     }
58      
59 }

 

 

二、还有一种是C#编码格式:GBK和UTF-8 两种,可惜这个解决老对不上,也有可以是对JAVA的加密方式和我们要求的不一样。

 1        //加密
public static string DESEncode(string encryptString, string encryptKey) 2 { 3 if (encryptKey.Length != 8) 4 { 5 return null; 6 } 7 DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); 8 byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey); 9 byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); 10 //byte[] rgbKey = Encoding.GetEncoding("GBK").GetBytes(encryptKey); 11 //byte[] inputByteArray = Encoding.GetEncoding("GBK").GetBytes(encryptString); 12 13 MemoryStream mStream = new MemoryStream(); 14 CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, new byte[8]), CryptoStreamMode.Write); 15 cStream.Write(inputByteArray, 0, inputByteArray.Length); 16 cStream.FlushFinalBlock(); 17 return Convert.ToBase64String(mStream.ToArray()); 18 } 19     //解密 20 public static string DESDecode(string decryptString, string decryptKey) 21 { 22 if (decryptKey.Length != 8) 23 { 24 return null; 25 } 26 byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey); 27 //byte[] rgbKey = Encoding.GetEncoding("GBK").GetBytes(decryptKey); 28 byte[] inputByteArray = Convert.FromBase64String(decryptString); 29 30 DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); 31 MemoryStream mStream = new MemoryStream(); 32 CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, new byte[8]), CryptoStreamMode.Write); 33 cStream.Write(inputByteArray, 0, inputByteArray.Length); 34 cStream.FlushFinalBlock(); 35 return Encoding.GetEncoding("utf-8").GetString(mStream.ToArray()); 36 }

JAVA

 

 

三、工具:还有各种加密

分别用C#、Java实现的RSA和DES加解密算法等。

 

亲试通过,放心使用……

 

posted @ 2022-01-11 17:08  Q玲珑  阅读(842)  评论(0编辑  收藏  举报