网站首页 > 软文百科 > 超实用的Java加解密工具,赶紧学习收藏吧(加解密工具)

超实用的Java加解密工具,赶紧学习收藏吧(加解密工具)

2023-04-06 12:20 发布

@Java讲坛杨33

引入加解密的目的

实际开发中,经常涉及一些业务数据是具有隐私性的,并且不情愿被外人看到这些隐私信息。所以使用Java语言开发,就必须在开发具体业务逻辑代码的时候,引入加解密的工具,把隐私数据保护起来。

下面就用编码封装我常用的两个加解密工具类DES、AES。

DES加解密

DES是一种对称的加解密算法。对称的意思就是加密和解密使用的密钥key是相同的。

直接上工具类代码:

import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;/** * DES加解密工具类 */public class Des3Util {private static final String ALGORITHM = "DESede";private static final String ENCODING = "UTF-8";private static final String HEX_SOURCE = "0123456789ABCDEF";/** * 字节码转十六进制字符串 * @param sources 字节码 * @return */private static String byteToHex(byte[] sources) {if(sources == null || sources.length == 0){return null;}StringBuffer result = new StringBuffer();for(byte source : sources){String tmp = (Integer.toHexString(source & 0XFF));if(tmp.length() == 1){result.append("0" tmp);}else{result.append(tmp);}}return result.toString().toUpperCase();}/** * 十六进制字符串转字节码 * @param source 十六进制字符串 * @return */public static byte[] hexToByte(String source) {if(source.length() % 2 != 0){throw new IllegalArgumentException("给定的十六进制字符串的长度不是偶数");}char[] sourceChars = source.toUpperCase().toCharArray();int length = sourceChars.length/2;byte buffer[] = new byte[length];for(int index = 0;index < length; index ) {buffer[index] = (byte) (HEX_SOURCE.indexOf(sourceChars[index*2]) << 4 | HEX_SOURCE.indexOf(sourceChars[index*2 1]));}return buffer;}/** * 根据密钥字符串生成密钥字节数组 * @param key 密钥 * @return 密钥字节数组 * @throws Exception */ private static byte[] buildDesKey(String key) throws Exception { byte[] keyByte = new byte[24]; byte[] temp = key.getBytes(ENCODING); if (keyByte.length > temp.length) { //如果temp不够24位,则拷贝temp数组整个长度的内容到key数组中 System.arraycopy(temp, 0, keyByte, 0, temp.length); } else { //如果temp大于24位,则拷贝temp数组24个长度的内容到key数组中 System.arraycopy(temp, 0, keyByte, 0, keyByte.length); } return keyByte; }/** * 加密 * @param source 待加密的字符串 * @param key 密钥 * @return 加密后的字符串 * @throws Exception */public static String encode(String source, String key) throws Exception {byte[] text = source.getBytes(ENCODING);Cipher cipher = Cipher.getInstance(ALGORITHM "/CBC/PKCS5Padding");SecretKey secretKey = new SecretKeySpec(buildDesKey(key), ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));byte[] cipherBytes = cipher.doFinal(text);return byteToHex(cipherBytes);}/** * 解密 * @param source 待解密的加密串 * @param key 密钥 * @return 解密后的字符串 * @throws Exception */public static String decode(String source, String key) throws Exception {Cipher cipher = Cipher.getInstance(ALGORITHM "/CBC/PKCS5Padding");SecretKey secretKey = new SecretKeySpec(buildDesKey(key), ALGORITHM);cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));return new String(cipher.doFinal(hexToByte(source)));}/** * 测试DES加解密 * @param args * @throws Exception */public static void main(String[] args) throws Exception {String key = "8681d91f1d56458385c9fc23b221828b";//加密System.out.println(encode("马云", key));//解密System.out.println(decode("1E27D89F0421A8A6", key));}}AES加解密

AES是DES的加强版,比DES的加解密强度更高。

直接上工具类代码:

import java.security.SecureRandom;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.spec.SecretKeySpec;/** * AES加解密工具类 */public class AesUtil {/** * 秘钥长度 */private static final int keysize = 128;/** * 加密方式 */private static final String algorithm = "AES";/** * 编码方式 */private static final String charSet = "UTF-8";/** * 十六进制字符 */private static final String HEX_SOURCE = "0123456789ABCDEF";/** * 加密 * @param source 待加密字符串 * @param key 秘钥 * @return 加密完的十六进制字符串;如果加密失败返回空 */public static String encrypt(String source, String key) { if(source == null || source.trim().length() == 0 || key == null || key.trim().length() == 0){return null;}try{KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");secureRandom.setSeed(key.getBytes());keyGenerator.init(keysize, secureRandom);SecretKeySpec secretKeySpec = new SecretKeySpec(keyGenerator.generateKey().getEncoded(), algorithm);Cipher cipher = Cipher.getInstance(algorithm);cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);byte[] sourceByte = cipher.doFinal(source.getBytes(charSet));return byteToHex(sourceByte);}catch(Exception e){System.err.println(e);return null;}} /** * 解密 * @param source 待解密十六进制字符串 * @param key 秘钥 * @return 加密后的字符串;如果解密失败返回null */public static String decrypt(String source, String key) { if(source == null || source.trim().length() == 0 || key == null || key.trim().length() == 0){return null;}try{byte[] sourceByte = hexToByte(source); KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");secureRandom.setSeed(key.getBytes());keyGenerator.init(keysize, secureRandom);SecretKeySpec secretKeySpec = new SecretKeySpec(keyGenerator.generateKey().getEncoded(), algorithm);Cipher cipher = Cipher.getInstance(algorithm);cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);return new String(cipher.doFinal(sourceByte),"UTF-8");}catch(Exception e){return null;}}/** * 字节码转十六进制字符串 * @param sources 字节码 * @return */private static String byteToHex(byte[] sources) {if(sources == null || sources.length == 0){return null;}StringBuffer result = new StringBuffer();for(byte source : sources){String tmp = (Integer.toHexString(source & 0XFF));if(tmp.length() == 1){result.append("0" tmp);}else{result.append(tmp);}}return result.toString().toUpperCase();}/** * 十六进制字符串转字节码 * @param source 十六进制字符串 * @return */private static byte[] hexToByte(String source){if(source.length() % 2 != 0){throw new IllegalArgumentException("给定的十六进制字符串的长度不是偶数");}char[] sourceChars = source.toUpperCase().toCharArray();int length = sourceChars.length/2;byte buffer[] = new byte[length];for(int index = 0;index < length;index ) {buffer[index] = (byte) (HEX_SOURCE.indexOf(sourceChars[index*2]) << 4 | HEX_SOURCE.indexOf(sourceChars[index*2 1]));}return buffer;}/** * 测试AES加解密 * @param args */public static void main(String[] args) {String key = "8681d91f1d56458385c9fc23b221828b";//加密System.out.println(encrypt("马云", key));//解密System.out.println(decrypt("DBBDAAE0F2B2999E0CA47CB3B7698C38", key));}}

到此,本次知识分享就结束了,谢谢大家对我的创作方面的鼓励。我会继续努力。

作者:杨33,北京互联网公司在职Java开发,专注分享写作干货。欢迎关注我,期待你的点赞评论。

以上内容为【超实用的Java加解密工具,赶紧学习收藏吧(加解密工具)】的相关内容,更多相关内容关注容和商贸通

免责声明:

本文内容来自用户上传并发布或网络新闻客户端自媒体,本站点仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请联系删除。

推荐问答