JAVA AES CBC PKCS5Padding 복호화

7602 단어
package com.hzxc.groupactivity.util;

/**
 * Created by hdwang on 2019/1/17.
 */
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


/**
 *       
 */
public class AESUtil {
    private static final Logger logger = LoggerFactory.getLogger(AESUtil.class);

    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";//       

    /**
     * AES     
     *
     * @param content      
     * @param password     
     * @param iv   CBC  ,      iv,          
     * @return     
     */
    public static byte[] encrypt(String content, String password,String iv) {
        try {
            //     
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

            //  key(  16   128bit key,    jre  local_policy.jar US_export_policy.jar,    :Illegal key size)
            SecretKeySpec keySpec = new SecretKeySpec(password.getBytes("utf-8"),KEY_ALGORITHM);

            //  iv
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));

            //            
            cipher.init(Cipher.ENCRYPT_MODE,keySpec,ivParameterSpec);

            //  
            byte[] byteContent = content.getBytes("utf-8");
            byte[] result = cipher.doFinal(byteContent);

            return result;
        } catch (Exception ex) {
            logger.error(ex.getMessage(),ex);
        }

        return null;
    }

    /**
     * AES     
     *
     * @param content   
     * @param password   
     * @param iv   CBC  ,      iv,          
     * @return   
     */
    public static String decrypt(byte[] content, String password,String iv) {

        try {
            //     
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

            //  key
            SecretKeySpec keySpec = new SecretKeySpec(password.getBytes("utf-8"),KEY_ALGORITHM);

            //  iv
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));

            //            
            cipher.init(Cipher.DECRYPT_MODE,keySpec,ivParameterSpec);

            //    
            byte[] result = cipher.doFinal(content);

            return new String(result,"utf-8");
        } catch (Exception ex) {
            logger.error(ex.getMessage(),ex);
        }

        return null;
    }



}

참조 사이트 주소:
https://www.cnblogs.com/lilinzhiyu/p/8024100.html

좋은 웹페이지 즐겨찾기