例子:
package com.yx.encryption;import org.Apache.commons.codec.binary.Base64;import javax.crypto.Cipher;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESedeKeySpec;import javax.crypto.spec.IvParameterSpec;import java.nio.charset.StandardCharsets;import java.security.Key;/** * DES3使用例子 * 加密和解密 * * @author yx */public class DES3Demo {/*** 密钥(24位)*/private static String SECRET_KEY = "123456781234567812345678";private static final String KEY_ALGORITHM = "DESede";private static final String CIPHER_ALGORITHM = "DESede/CBC/PKCS5Padding";/*** 3DES 加密** @param key密钥(24位)* @param iv偏移量* @param data 需要加密的字符串* @return 返回加密的字符串*/public static String encrypt(String key, String iv, String data) {try {DESedeKeySpec spec = new DESedeKeySpec(key.getBytes(StandardCharsets.UTF_8));SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);Key desKey = keyFactory.generateSecret(spec);Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);IvParameterSpec ips = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));cipher.init(Cipher.ENCRYPT_MODE, desKey, ips);byte[] bOut = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));return Base64.encodeBase64String(bOut);} catch (Exception e) {e.printStackTrace();System.out.println("3DES 解密错误");throw new RuntimeException("3DES 解密错误");}}/*** 3DES 解密** @param key密钥(24位)* @param iv偏移量* @param data 需要解密的密文* @return 返回加密的字符串*/public static String decrypt(String key, String iv, String data) {try {DESedeKeySpec spec = new DESedeKeySpec(key.getBytes(StandardCharsets.UTF_8));SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);Key desKey = keyFactory.generateSecret(spec);Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);IvParameterSpec ips = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));cipher.init(Cipher.DECRYPT_MODE, desKey, ips);byte[] bOut = cipher.doFinal(Base64.decodeBase64(data.getBytes(StandardCharsets.UTF_8)));return new String(bOut, StandardCharsets.UTF_8);} catch (Exception e) {e.printStackTrace();System.out.println("3DES 解密错误");throw new RuntimeException("3DES 解密错误");}}public static void main(String[] args) {String data = https://www.isolves.com/it/cxkf/sf/2021-07-30/"EasyJava";String des3EncodeCBC = encrypt(SECRET_KEY, "53152654", data);System.out.println("加密结果:" + des3EncodeCBC);String des3DecodeCBC = decrypt(SECRET_KEY, "53152654", des3EncodeCBC);System.out.println("解密结果:" + des3DecodeCBC);}}执行结果:加密结果:5GBjg/fcZ45YrGKm8nxHvQ==解密结果:EasyJava
3、AES
说明:是目前对称加密算法中最流行的算法之一 , 是DES的替代者 , 未被破解 , 性能更优 。
例子:
package com.yx.encryption;import javax.crypto.Cipher;import javax.crypto.spec.SecretKeySpec;import java.security.Key;import java.util.Base64;/** * AES使用例子 * 加密和解密 * * @author yx */public class AESDemo {/*** 密钥(24)*/private static String SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxxxx";public static void main(String[] args) throws Exception {// 加密字符串String src = https://www.isolves.com/it/cxkf/sf/2021-07-30/"EasyJava";// Key转换Key key = new SecretKeySpec(SECRET_KEY.getBytes("utf-8"), "AES");// 加密Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");cipher.init(Cipher.ENCRYPT_MODE, key);byte[] encryptBytes = cipher.doFinal(src.getBytes("utf-8"));System.out.println("加密结果:" + Base64.getEncoder().encodeToString(encryptBytes));// 解密cipher.init(Cipher.DECRYPT_MODE, key);byte[] decodeBytes = cipher.doFinal(encryptBytes);System.out.println("解密结果:" + new String(decodeBytes));}}执行结果:加密结果:ESuCYW2piOpf4Expba6IuA==解密结果:EasyJava
四、非对称加解密
1、RSA
说明:广泛接受且实现 , 多用于数据加密和数字签名领域 , 支持公钥加密私钥解密 , 私钥加密公钥解密方式 。
例子:
package com.yx.encryption;import javax.crypto.Cipher;import java.security.*;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.Base64;/** * RSA使用例子 * 私钥加密 , 公钥解密 * 公钥加密 , 私钥解密 * * @author yx */public class RSADemo {private static void encode1(String src, RSAPublicKey rsaPublicKey, RSAPrivateKey rsaPrivateKey) throws Exception {// 加密PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());KeyFactory keyFactory = KeyFactory.getInstance("RSA");PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, privateKey);byte[] encodeResult = cipher.doFinal(src.getBytes("utf-8"));System.out.println("【私钥加密、公钥解密】加密结果:" + Base64.getEncoder().encodeToString(encodeResult));// 解密X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());keyFactory = KeyFactory.getInstance("RSA");PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, publicKey);byte[] decodeResult = cipher.doFinal(encodeResult);System.out.println("【私钥加密、公钥解密】解密结果:" + new String(decodeResult, "utf-8"));}private static void encode2(String src, RSAPublicKey rsaPublicKey, RSAPrivateKey rsaPrivateKey) throws Exception {// 加密X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());KeyFactory keyFactory = KeyFactory.getInstance("RSA");PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] encodeResult = cipher.doFinal(src.getBytes("utf-8"));System.out.println("【公钥加密、私钥解密】加密结果:" + Base64.getEncoder().encodeToString(encodeResult));// 解密PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());keyFactory = KeyFactory.getInstance("RSA");PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] decodeResult = cipher.doFinal(encodeResult);System.out.println("【公钥加密、私钥解密】解密结果:" + new String(decodeResult, "utf-8"));}public static void main(String[] args) throws Exception {// 加密字符串String src = https://www.isolves.com/it/cxkf/sf/2021-07-30/"EasyJava";KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");keyPairGenerator.initialize(512);KeyPair keyPair = keyPairGenerator.generateKeyPair();// 公钥 & 私钥RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();System.out.println("公钥:" + Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded()));System.out.println("私钥:" + Base64.getEncoder().encodeToString(rsaPrivateKey.getEncoded()));// 【私钥加密、公钥解密】encode1(src, rsaPublicKey, rsaPrivateKey);// 【公钥加密、私钥解密】encode2(src, rsaPublicKey, rsaPrivateKey);}}执行结果:公钥:MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJ68MgEMZD7X+5e9kYwLZfcXeCzlXlB3me/v214mON3ONbDjX++a3b7EqW+rVf49H9AmiY5bWuj335X/18/qyV8CAwEAAQ==私钥:MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEAnrwyAQxkPtf7l72RjAtl9xd4LOVeUHeZ7+/bXiY43c41sONf75rdvsSpb6tV/j0f0CaJjlta6Pfflf/Xz+rJXwIDAQABAkAnJACwgX22gUtofzYEcksSQpc/es9myBcNMvfEn2gmSO8wYDxTnyctYGC0slOjFXDSuTp5WoK/bRcAOWnDI/UBAiEA0uQJeMGpl5c8Qmbxs5NWJvXOntJE/S/Ka/1UgX/MJXUCIQDAsDf9rUDxzjF+hqY9Mv79STO3PYd5MZN/C3uHCGzVAwIgDf6d9kp7s5iQoiNstKr5U5qKPJXdiCOsvh/QhMtzQ6UCIFkiKwRh3KT+aM7KoqO0r1ejQRUGlWBumngua5nvP8jZAiBcdQ1czDuqBPQrua0DylFeP/3way2pKrQFg4xmNcM8Uw==【私钥加密、公钥解密】加密结果:KjQIb91tWcau+FAwPF6AX6jw3QzYhXyaQQPG6roNWZ5wT1nMhanX2G1O2ZNPqVS2s3Ar4Cl1ROKYF6JmlEeYBw==【私钥加密、公钥解密】解密结果:EasyJava【公钥加密、私钥解密】加密结果:gw3PUe2zrCsZ+SyIgGBPX2ZnzQVnTZal7pvP4TZRGUzQho2IK91YjdbV8ec9Tp9HUHKVHMf96aNu2tRc7ZDMBg==【公钥加密、私钥解密】解密结果:EasyJava
推荐阅读
- 「Java原理探索」「AQS」教你自定义实现自己的同步器
- Java循环结构——switch语句
- Javascript 中New 操作符 解读
- 不仅限于Java 我们必须要了解的Java位运算
- 关于加密算法你了解多少
- 为什么我们总是推荐Java?Java为什么值得学?
- 学Java还是前端?我是这么看的
- Java开发环境搭建与配置,最全手册看这一篇就够了
- 彻底搞懂Java线程池的工作原理
- Java主要的5个标准注解如何使用?