你好,游客 登录 注册 搜索
背景:
阅读新闻

Java加密算法AES与RSA

[日期:2017-12-24] 来源:Linux社区  作者:svili [字体: ]

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 测试代码

public static void test1() throws Exception {
        KeyPair keyPair = RSAUtil.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 明文
        String text = "hello , AES";
        // 公钥加密明文-->密文
        byte[] encrypted = RSAUtil.encrypt(text.getBytes(), publicKey);

        // 私钥解密密文-->明文
        byte[] decrypted = RSAUtil.decrypt(encrypted, privateKey);

        System.out.println(new String(decrypted, CharsetConstants.UTF_8));
    }

    public static void test2() throws Exception {
        KeyPair keyPair = RSAUtil.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 明文
        String text = "hello , AES";

        PublicKey publicKey2 = RSAUtil.getPublicKey(publicKey.getModulus(), publicKey.getPublicExponent());
        // 公钥加密明文-->密文
        byte[] encrypted = RSAUtil.encrypt(text.getBytes(), publicKey2);

        PrivateKey privateKey2 = RSAUtil.getPrivateKey(privateKey.getModulus(), privateKey.getPrivateExponent());

        // 私钥解密密文-->明文
        byte[] decrypted = RSAUtil.decrypt(encrypted, privateKey2);

        System.out.println(new String(decrypted, CharsetConstants.UTF_8));
    }

    public static void test3() throws Exception {
        KeyPair keyPair = RSAUtil.generateKeyPair();
        PublicKey publicKey = RSAUtil.getPublicKey(keyPair.getPublic().getEncoded());
        PrivateKey privateKey = RSAUtil.getPrivateKey(keyPair.getPrivate().getEncoded());
        // 明文
        String text = "hello , AES";

        // 公钥加密明文-->密文
        byte[] encrypted = RSAUtil.encrypt(text.getBytes(), publicKey);

        // 私钥解密密文-->明文
        byte[] decrypted = RSAUtil.decrypt(encrypted, privateKey);

        System.out.println(new String(decrypted, CharsetConstants.UTF_8));
    }

本文永久更新链接地址http://www.linuxidc.com/Linux/2017-12/149759.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款