如何在Java项目中实现一个DES加密算法?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。Base64.javapackage com.mstf.des; import java
如何在Java项目中实现一个DES加密算法?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
Base64.java
package com.mstf.des; import java.io.UnsupportedEncodingException; public class Base64 { public static String encode(String data) { return new String(encode(data.getBytes())); } public static String decode(String data) { try { return new String(decode(data.toCharArray()),"utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } private static char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" .toCharArray(); private static byte[] codes = new byte[256]; static { for (int i = 0; i < 256; i++) { codes[i] = -1; } for (int i = 'A'; i <= 'Z'; i++) { codes[i] = (byte) (i - 'A'); } for (int i = 'a'; i <= 'z'; i++) { codes[i] = (byte) (26 + i - 'a'); } for (int i = '0'; i <= '9'; i++) { codes[i] = (byte) (52 + i - '0'); } codes['+'] = 62; codes['/'] = 63; } public static char[] encode(byte[] data) { char[] out = new char[((data.length + 2) / 3) * 4]; for (int i = 0, index = 0; i < data.length; i += 3, index += 4) { boolean quad = false; boolean trip = false; int val = (0xFF & (int) data[i]); val <<= 8; if ((i + 1) < data.length) { val |= (0xFF & (int) data[i + 1]); trip = true; } val <<= 8; if ((i + 2) < data.length) { val |= (0xFF & (int) data[i + 2]); quad = true; } out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)]; val >>= 6; out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)]; val >>= 6; out[index + 1] = alphabet[val & 0x3F]; val >>= 6; out[index + 0] = alphabet[val & 0x3F]; } return out; } public static byte[] decode(char[] data) { int tempLen = data.length; for (int ix = 0; ix < data.length; ix++) { if ((data[ix] > 255) || codes[data[ix]] < 0) { --tempLen; } } int len = (tempLen / 4) * 3; if ((tempLen % 4) == 3) { len += 2; } if ((tempLen % 4) == 2) { len += 1; } byte[] out = new byte[len]; int shift = 0; int accum = 0; int index = 0; for (int ix = 0; ix < data.length; ix++) { int value = (data[ix] > 255) ? -1 : codes[data[ix]]; if (value >= 0) { accum <<= 6; shift += 6; accum |= value; if (shift >= 8) { shift -= 8; out[index++] = (byte) ((accum >> shift) & 0xff); } } } if (index != out.length) { throw new Error("Miscalculated data length (wrote " + index + " instead of " + out.length + ")"); } return out; }}
--结束END--
本文标题: 如何在Java项目中实现一个DES加密算法
本文链接: https://www.lsjlt.com/news/225590.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-21
2024-05-21
2024-05-21
2024-05-21
2024-05-21
2024-05-21
2024-05-21
2024-05-21
2024-05-21
2024-05-21
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0