java 加密解密代码_JAVA加密解密代码 - 日理万妓 2022-11-05 10:55 179阅读 0赞 import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class MyDes \{ // 定义 加密算法 private static final String Algorithm = "DESede"; private String key = "wjdkseibheyskgvxhtes;gys"; private byte \[\] keybyte = key.getBytes(); /\*\*\* \* 加密 \* @param keybyte 加密密钥,长度为24字节 \* @param pwd 被加密的数据 \* @return \*/ private byte\[\] encryptMode(byte\[\] keybyte,String pwd) \{ byte\[\] src = pwd.getBytes(); try \{ // 生成密钥 SecretKey deskey = new SecretKeySpec(keybyte, Algorithm); // 加密 Cipher c1 = Cipher.getInstance(Algorithm); c1.init(Cipher.ENCRYPT\_MODE, deskey); return c1.doFinal(src); \} catch (Exception e1) \{ e1.printStackTrace(); \} return null; \} /\*\*\* \* 解密 \* @param keybyte 密钥 \* @param src 加密后的缓冲源 \* @return \*/ private byte\[\] decryptMode(byte\[\] keybyte,byte\[\] src) \{ try \{ // 生成密钥 SecretKey deskey = new SecretKeySpec(keybyte, Algorithm); // 解密 Cipher c1 = Cipher.getInstance(Algorithm); c1.init(Cipher.DECRYPT\_MODE, deskey); return c1.doFinal(src); \} catch (Exception e1) \{ \} return null; \} // 转换成十六进制字符串 private String byte2hex(byte\[\] b) \{ String hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) \{ stmp = (java.lang.Integer.toHexString(b\[n\] & 0XFF)); if (stmp.length() == 1) hs = hs + "0" + stmp; else hs = hs + stmp; if (n < b.length - 1) hs = hs + ""; \} return hs.toUpperCase(); \} /\*\*\* \* 返回加密后的字符串 \* @param pwd \* @return \*/ public String encrypt(String pwd)\{ return new String(this.encryptMode(keybyte, pwd)); \} /\*\*\* \* 根据密码生成cookie中保存的字符串 \* @param pwd \* @return \*/ public String getCoookieString(String pwd)\{ byte\[\] encoded = this.encryptMode(keybyte, pwd); StringBuffer sb = new StringBuffer(); for (int i = 0; i < encoded.length; i++) \{ sb.append(encoded\[i\]); if(i!=(encoded.length-1))\{ sb.append("&"); \} \} return sb.toString(); \} /\*\*\* \* 把cookie中的字符串变成解密用的byte\[\]数组 \* @param cookieString \* @return \*/ private byte\[\] getCookieByte(String cookieString)\{ String \[\] s = cookieString.split("&"); byte\[\] en = new byte\[s.length\] ; for (int i = 0; i < s.length; i++) \{ en\[i\] = Byte.parseByte(s\[i\]); \} return en; \} public String decrypt(String pwds)\{ byte\[\] en = this.getCookieByte(pwds); return new String(this.decryptMode(keybyte, en)); \} \}
还没有评论,来说两句吧...