TripleDES在java与c#中的区别

       C#下TripleDES默认支持16位和24位的秘钥,而Java下的DESedeKeySpec就只支持24位,其实怎么说呢,按3DES规范要求,的确其秘钥应该是24位而不是16位的,但16位秘钥可以按 前8位+后8位+前8位 的规则来升级成24位的秘钥,所以我们只需要简单的通过数组的Copy就可以将16位秘钥升级为24位秘钥,下面是相应的代码,Java和C#可以说完全一样,C#16位秘钥加密的结果可以用C#(或Java)24位秘钥的来解密
 

 1         /// <summary>
 2         /// 尝试将16位的3DES秘钥升级成24位秘钥
 3         /// </summary>
 4         /// <param name="inputKey">16位秘钥</param>
 5         /// <param name="outputKey">24位秘钥,如果失败则返回null</param>
 6         /// <returns></returns>
 7         public static bool TryPromotion16To24(byte[] inputKey, out byte[] outputKey)
 8         {
 9             outputKey = null;
10             if (inputKey != null && inputKey.Length == 16)
11             {
12                 outputKey = new byte[24];
13                 Array.Copy(inputKey, 0, outputKey, 0, 16);
14                 Array.Copy(inputKey, 0, outputKey, 16, 8);
15                 return true;
16             }
17             return false;
18         }

 

 1     /**
 2      * 将3DES的16位秘钥升级为24位秘钥
 3      * @param inputKey 16位秘钥
 4      * @return 24位秘钥
 5      * @throws IllegalArgumentException
 6      */
 7     static byte[] promotion16To24(byte[] inputKey)
 8             throws IllegalArgumentException {
 9         if (inputKey == null || inputKey.length != 16) {
10             throw new IllegalArgumentException("input error");
11         }
12         byte[] outputKey = new byte[24];
13         System.arraycopy(inputKey, 0, outputKey, 0, 16);
14         System.arraycopy(inputKey, 0, outputKey, 16, 8);
15         return outputKey;
16     

 

然而,上面只是常规做法,实际应用中还有一种方法,这种做法没碰过的还真想不出来,那就是将秘钥转为base64字符串,稍加注意就会发现 16位的秘钥转为base64后,长度是24位,所以这时候只要将字符串简单粗暴的转为byte[]就是一个合法的3DES秘钥……

Encoding.UTF8.GetBytes(base64Str)

 

base64Str.getBytes("UTF-8")


原文链接:https://blog.csdn.net/starfd/article/details/78783709

posted @ 2023-12-20 09:58  hobby0524  阅读(7)  评论(0编辑  收藏  举报