Java加密算法AES与RSA

Java加密算法AES与RSA 1.commons-codec使用

commons-codes 常用工具类:DigestUtils,Base64,Hex

1.1 md5

String text = "hello,md5"; DigestUtils.md5Hex(text);

1.2 sha1

String text = "hello,sha1"; DigestUtils.sha1Hex(text);

1.3 base64

用于加密的明文必须是字节数组(byte[]),加解密算法可以返回字节数组(byte[])和字符串(String)两种格式的数据。

//明文 String text="hello,base64"; byte[] byteArray= text.getBytes(Charset.forName("utf-8")); //明文加密-->密文 byte[] encryptedData = Base64.encodeBase64(byteArray); //密文解密-->明文 byte[] decryptedData = Base64.decodeBase64(encryptedData); //明文加密-->密文 String encryptedString = Base64.encodeBase64String(byteArray); //密文解密-->明文 String decryptedString =Base64.decodeBase64(encryptedString); 

2.AES对称加密 2.1 代码

/*** * AES加解密 * * @author svili * @date 2017年9月8日 * */ public class AESUtil { private static class GeneratorHolder { /** AES秘钥生成器 */ private static KeyGenerator keyGenerator; static { // 静态内部类实现单例模式 try { keyGenerator = KeyGenerator.getInstance("AES"); } catch (NoSuchAlgorithmException e) { LogUtil.error("KeyGenerator fro AES init error.", e); } // AES秘钥长度:128bit(位)=16byte(字节) keyGenerator.init(128); } } public static KeyGenerator getGenerator() { return GeneratorHolder.keyGenerator; } public static byte[] generateKey() { SecretKey secretKey = getGenerator().generateKey(); return secretKey.getEncoded(); } public static byte[] encrypt(byte[] data, byte[] encodedKey) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException { // 初始化加密算法 SecretKeySpec keySpec = new SecretKeySpec(encodedKey, "AES"); Cipher cipher = getCipher(); cipher.init(Cipher.ENCRYPT_MODE, keySpec); // 加密 return cipher.doFinal(data); } public static byte[] decrypt(byte[] data, byte[] encodedKey) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException { // 初始化解密算法 SecretKeySpec keySpec = new SecretKeySpec(encodedKey, "AES"); Cipher cipher = getCipher(); cipher.init(Cipher.DECRYPT_MODE, keySpec); // 解密 return cipher.doFinal(data); } public static Cipher getCipher() { Cipher cipher = null; try { cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); } catch (NoSuchAlgorithmException e) { } catch (NoSuchPaddingException e) { } return cipher; } }

2.2 测试代码

     
     //生成秘钥
     byte
[] key = AESUtil.generateKey(); // 明文 String text = "hello , AES"; // 密文 byte[] encrypted = AESUtil.encrypt(text.getBytes(), key); System.out.println(new String(encrypted, CharsetConstants.UTF_8)); // 解密密文-->明文 byte[] decrypted = AESUtil.decrypt(encrypted, key); System.out.println(new String(decrypted, CharsetConstants.UTF_8)); 

3.RSA非对称加密 3.1 代码

/*** * RSA加解密</br> * <ul> * RSA数据加解密方式 * <li>1.明文-->公钥加密-->密文-->私钥解密-->明文 * <li>2.明文-->私钥加密-->密文-->公钥解密-->明文 * <ul> * SRA密钥说明 * <li>相关参数:公钥指数publicExponent,私钥指数privateExponent,模值modulus * <li>key = fun(modulus,exponent) {@link #getPublicKey(BigInteger, BigInteger)} * <li>key = fun(encodedKey) {@link #getPublicKey(byte[])} * * @author svili * @date 2017年9月8日 * */ public class RSAUtil { /** RSA密文长度:128byte(字节) */ private final static int DECRYPT_BLOCK_CAPACITY = 2 << 6; /** RSA明文长度:117byte(字节),padding=11byte(字节) */ private final static int ENCRYPT_BLOCK_CAPACITY = (2 << 6) - 11; private static class GeneratorHolder { /** RSA秘钥生成器 */ private static KeyPairGenerator keyPairGenerator; static { // 静态内部类实现单例模式 try { keyPairGenerator = KeyPairGenerator.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { keyPairGenerator = null; LogUtil.error("KeyGenerator fro RSA init error.", e); } // 模值长度 keyPairGenerator.initialize(1024); } } public static KeyPairGenerator getGenerator() { return GeneratorHolder.keyPairGenerator; } public static KeyPair generateKeyPair() { // 生成密钥对 return getGenerator().generateKeyPair(); } public static Cipher getCipher() { Cipher cipher = null; try { // 算法/模式/填充 cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); } catch (NoSuchAlgorithmException e) { } catch (NoSuchPaddingException e) { } return cipher; } /*** * 加密/解密算法 </br> * <ul> * RSA算法中,对明文/密文的字节长度有所限制,超过最大长度需要分段处理. * <li>密文最大字节长度为:{@value #DECRYPT_BLOCK_CAPACITY} * <li>明文最大字节长度为:{@value #ENCRYPT_BLOCK_CAPACITY} * * @param blockCapacity * 块的容量(最大字节长度) * @throws IllegalBlockSizeException * @throws BadPaddingException */ private static byte[] doFinalInternal(byte[] data, Cipher cipher, int blockCapacity) throws IllegalBlockSizeException, BadPaddingException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(2 << 6); int offset = 0; int waitResolveLength = 0; while ((waitResolveLength = data.length - offset) > 0) { byte[] resolved; if (waitResolveLength < blockCapacity) { resolved = cipher.doFinal(data, offset, waitResolveLength); } else { resolved = cipher.doFinal(data, offset, blockCapacity); } try { outputStream.write(resolved); } catch (IOException e) { throw new RuntimeException(e); } offset += blockCapacity; } return outputStream.toByteArray(); } /** * 数据加密 * * @throws InvalidKeyException * @throws BadPaddingException * @throws IllegalBlockSizeException * */ public static byte[] encrypt(byte[] data, Key key) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = getCipher(); // 加密模式 cipher.init(Cipher.ENCRYPT_MODE, key); // 执行加密算法 return doFinalInternal(data, cipher, ENCRYPT_BLOCK_CAPACITY); } /** * 数据解密 * * @throws InvalidKeyException * @throws BadPaddingException * @throws IllegalBlockSizeException * */ public static byte[] decrypt(byte[] data, Key key) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = getCipher(); cipher.init(Cipher.DECRYPT_MODE, key); return doFinalInternal(data, cipher, DECRYPT_BLOCK_CAPACITY); } public static PublicKey getPublicKey(BigInteger modulus, BigInteger exponent) throws NoSuchAlgorithmException, InvalidKeySpecException { RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(keySpec); } public static PrivateKey getPrivateKey(BigInteger modulus, BigInteger exponent) throws NoSuchAlgorithmException, InvalidKeySpecException { RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(modulus, exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(keySpec); } public static PublicKey getPublicKey(byte[] encodedKey) throws NoSuchAlgorithmException, InvalidKeySpecException { // X509 X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(keySpec); } public static PrivateKey getPrivateKey(byte[] encodedKey) throws NoSuchAlgorithmException, InvalidKeySpecException { // PKCS8 PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(keySpec); } }

3.2 测试代码

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/83210ea8a58343cfdbd66e388dda1f2e.html