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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~