加密算法一般分为对称性加密算法和非对称性加密算法,对于对称性加密算法,信息接收双方都需事先知道密匙和加解密算法且其密匙是相同的,以后即是对数据进行 加解密了。非对称算法与之不一样,发送双方A,B事先均生成一堆密匙,而后A将本身的公有密匙发送给B,B将本身的公有密匙发送给A,若是A要给B发送消 息,则先须要用B的公有密匙进行消息加密,而后发送给B端,此时B端再用本身的私有密匙进行消息解密,B向A发送消息时为一样的道理。java
DES是一种分组数据加密技术(先将数据分红固定长度的小数据块,以后进行加密),速度较快,适用于大量数据加密,而3DES是一种基于DES的加密算法,使用3个不一样密匙对同一个分组数据块进行3次加密,如此以使得密文强度更高。算法
相较于DES和3DES算法而言,AES算法有着更高的速度和资源使用效率,安全级别也较之更高了,被称为下一代加密标准。spring
RSA和DSA的安全性及其它各方面性能都差很少,而ECC较之则有着不少的性能优越,包括处理速度,带宽要求,存储空间等等。数组
这几种算法只生成一串不可逆的密文,常常用其效验数据传输过程当中是否通过修改,由于相同的生成算法对于同一明文只会生成惟一的密文,若相同算法生成的密文不一样,则证实传输数据进行过了修改。一般在数据传说过程前,使用MD5和SHA1算法均须要发送和接收数据双方在数据传送以前就知道密匙生成算法,而HMAC与之不一样的是须要生成一个密匙,发送方用此密匙对数据进行摘要处理(生成密文),接收方再利用此密匙对接收到的数据进行摘要处理,再判断生成的密文是否相同。安全
因为对称加密算法的密钥管理是一个复杂的过程,密钥的管理直接决定着他的安全性,所以当数据量很小时,咱们能够考虑采用非对称加密算法。app
在实际的操做过程当中,咱们一般采用的方式是:采用非对称加密算法管理对称算法的密钥,而后用对称加密算法加密数据,这样咱们就集成了两类加密算法的优势,既实现了加密速度快的优势,又实现了安全方便管理密钥的优势。dom
若是在选定了加密算法后,那采用多少位的密钥呢?性能
通常来讲,密钥越长,运行的速度就越慢,应该根据的咱们实际须要的安全级别来选择,通常来讲,RSA建议采用1024位的数字,ECC建议采用160位,AES采用128为便可。测试
import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class AESUtil { public static byte[] encrypt(String content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 建立密码器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } public static String encryptString(String content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 建立密码器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent); String encryptResultStr = parseByte2HexStr(result); return encryptResultStr; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } public static byte[] decrypt(byte[] content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 建立密码器 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(content); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } public static String decrypt(String content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] decryptFrom = parseHexStr2Byte(content); byte[] result = cipher.doFinal(decryptFrom); return new String(result); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } public static String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) return null; byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } public static void main(String[] args) { String content = "test"; String password = "12345678"; // 加密 System.out.println("加密前:" + content); byte[] encryptResult = encrypt(content, password); String encryptResultStr = parseByte2HexStr(encryptResult); System.out.println("加密后:" + encryptResultStr); // 解密 byte[] decryptFrom = parseHexStr2Byte(encryptResultStr); byte[] decryptResult = decrypt(decryptFrom, password); System.out.println("解密后:" + new String(decryptResult)); String enStr = encryptString("123", "@#&^%-$#@Coupon#$%^&@*"); System.out.println(enStr); } }
import java.security.MessageDigest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; public abstract class EncodeUtil { private static Logger logger = LoggerFactory.getLogger(EncodeUtil.class); /** * 定义加密方式 */ private final static String KEY_SHA = "SHA"; private final static String MD5 = "MD5"; /** * SHA 加密 * * @param data 须要加密的字符串 * @return 加密以后的字符串 */ public static String sha(String data) { // 验证传入的字符串 if (StringUtils.isEmpty(data)) { return ""; } try { // 建立具备指定算法名称的信息摘要 MessageDigest sha = MessageDigest.getInstance(KEY_SHA); // 使用指定的字节数组对摘要进行最后更新 sha.update(data.getBytes("utf-8")); // 完成摘要计算 byte[] bytes = sha.digest(); // 将获得的字节数组变成字符串返回 return byteArrayToHexString(bytes); } catch (Exception e) { logger.error("字符串使用SHA加密失败", e); return null; } } /** * MD5 加密 * * @param data 须要加密的字符串 * @return 加密以后的字符串 */ public static String md5(String source) { // 验证传入的字符串 if (StringUtils.isEmpty(source)) { return ""; } try { MessageDigest md = MessageDigest.getInstance(MD5); byte[] bytes = md.digest(source.getBytes("utf-8")); return byteArrayToHexString(bytes); } catch (Exception e) { logger.error("字符串使用Md5加密失败" + source + "' to MD5!", e); return null; } } /** * 转换字节数组为十六进制字符串 * * @param bytes * 字节数组 * @return 十六进制字符串 */ private static String byteArrayToHexString(byte[] bytes) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { sb.append(Integer.toHexString((bytes[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3)); } return sb.toString(); } /** * 测试方法 * * @param args */ public static void main(String[] args) throws Exception { String key = "123"; System.out.println(sha(key)); System.out.println(md5(key)); } }
参考:加密