AES 128加密解密共同处理类

package jp.hub.agk.core.encrypt;


public class EncryptConst {
 //暗号化方式
    public static final String KEY_ALGORITHM = "AES";
    //CBC初期ベクトル取得値
    public static final String IV = "1a0d2nc4a5ln0s0x";
    //鍵長
    public static final int KEY_SIZE = 128;
    //アルゴリズム値
    public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
    //コード
    public static final String CHAR_SET_UTF8 = "UTF-8";
    //ランダムシード
    public static final String RANDOM_SEED = "SHA1PRNG";
    //暗号化用キーのパスワード
    public static final String PASS = "1234567890123456";
    //暗号化用キー設定ファイル
    public static final String PATH = "/WEB-INF/encrypt_setting.txt";
    //空文字
    public static final String EMPTY_STRING = "";


    public static final String SPLITER = "=";
    public static final String CONFIG_KEY = "password";
}

 
 
 
 

  
  
package jp.hub.agk.core.encrypt;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.SecureRandom;


import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


import jp.hub.agk.core.SystemConfBean;
import jp.hub.agk.core.setting.CustomizeSetting;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * 暗号化・復号化用共通部品
 * @author admin
 *
 */
public class EncryptUtil {


    private static Log log = LogFactory.getLog(EncryptUtil.class);


 /**
 * 暗号化<br/>
 * 暗号化した文字列を返却する
 * @param content - 暗号対象文字列
 * @return エラーの場合nullを返却する
 */
 public static String encryptToString(String content) {
 //TODO レビュー待ちのため、一時に無効化する
 if (!CustomizeSetting.ENCRYPT_FLG) {
 return content;
 }
 try {
 if (content == null) {
 return null;
 }
 byte[] bytes = content.getBytes(EncryptConst.CHAR_SET_UTF8);
 String encryptString = encryptToString(bytes);
 return encryptString;
 } catch (Exception e) {
 log.error(e.getMessage());
 return null;
 }
 }


 /**
 * 暗号化<br/>
 * 暗号化した文字列を返却する
 * @param bytes - 暗号化するbyteストリーム
 * @return エラーの場合nullを返却する
 */
 public static String encryptToString(byte[] bytes) {
 //TODO レビュー待ちのため、一時に無効化する
 if (!CustomizeSetting.ENCRYPT_FLG) {
 return null;
 }
 try {
 if (bytes == null) {
 return null;
 }
 IvParameterSpec ivSpec = new IvParameterSpec(EncryptConst.IV.getBytes(EncryptConst.CHAR_SET_UTF8));
 Cipher cipher = Cipher.getInstance(EncryptConst.CIPHER_ALGORITHM, "SunJCE");
 cipher.init(Cipher.ENCRYPT_MODE, genKey(), ivSpec);
 byte[] resultByte = cipher.doFinal(bytes);
 String resultStr = parseByte2HexStr(resultByte);
 return resultStr;
 } catch (Exception e) {
 log.error(e.getMessage());
 return null;
 }
 }


 /**
 * 復号化<br>
 * 対象文字列の複号化を行い文字列を返却する
 * @param content - 複合化対象文字列
 * @return エラーの場合nullを返却する
 */
 public static String decryptToString(String content) {
 //TODO レビュー待ちのため、一時に無効化する
 if (!CustomizeSetting.ENCRYPT_FLG) {
 return content;
 }
 try {
 if (content == null) {
 return null;
 }
 byte[] bytes = parseHexStr2Byte(content);
 String decryptString = decryptToString(bytes);
 return decryptString;
 } catch (Exception e) {
 log.error(e.getMessage());
 return null;
 }
 }


 /**
 * 復号化<br>
 * 対象文字列の複号化を行い文字列を返却する
 * @param bytes
 * @return エラーの場合nullを返却する
 */
 public static String decryptToString(byte[] bytes) {
 //TODO レビュー待ちのため、一時に無効化する
 if (!CustomizeSetting.ENCRYPT_FLG) {
 return null;
 }
 try {
 if (bytes == null) {
 return null;
 }
 IvParameterSpec ivSpec = new IvParameterSpec(EncryptConst.IV.getBytes(EncryptConst.CHAR_SET_UTF8));
 Cipher cipher = Cipher.getInstance(EncryptConst.CIPHER_ALGORITHM, "SunJCE");
 cipher.init(Cipher.DECRYPT_MODE, genKey(), ivSpec);
 byte[] result = cipher.doFinal(bytes);
 String decryptString = new String(result, EncryptConst.CHAR_SET_UTF8);
 return decryptString;
 } catch (Exception e) {
 log.error(e.getMessage());
 return null;
 }
 }


 /**
 * AES暗号化用キー生成
 * @return
 */
 private static SecretKeySpec genKey(){
 byte[] enCodeFormat = {0};
 try {
 SystemConfBean confBean = SystemConfBean.getInstance();
 String password = confBean.getEncryptPassword();
 KeyGenerator kgen = KeyGenerator.getInstance(EncryptConst.KEY_ALGORITHM);
 SecureRandom secureRandom = SecureRandom.getInstance(EncryptConst.RANDOM_SEED);
 secureRandom.setSeed(password.getBytes());
 kgen.init(EncryptConst.KEY_SIZE, secureRandom);
 SecretKey secretKey = kgen.generateKey();
 enCodeFormat = secretKey.getEncoded();
 } catch (Exception e) {
 log.error(e.getMessage());
 }
 return new SecretKeySpec(enCodeFormat, EncryptConst.KEY_ALGORITHM);
 }


 /**
 * ファイルを読み込んで、復号化して、書き込む
 * @param File
 * @throws Exception
 */
 public static void writeDecrycptFile(File infile, File outFile) throws Exception{
 IvParameterSpec ivSpec = new IvParameterSpec(EncryptConst.IV.getBytes(EncryptConst.CHAR_SET_UTF8));
 Cipher cipher = Cipher.getInstance(EncryptConst.CIPHER_ALGORITHM, "SunJCE");
 cipher.init(Cipher.DECRYPT_MODE, genKey(), ivSpec);
 byte[] buffer = new byte[8192];
 CipherInputStream cin = new CipherInputStream(new FileInputStream(infile), cipher);
 FileOutputStream fos = new FileOutputStream(outFile);
        int read = cin.read(buffer);
        while(read != -1){
        	fos.write(buffer, 0, read);
            read = cin.read(buffer);
        }
        cin.close();
        fos.close();
 }


 /**
 * ファイルを読み込んで、暗号化して、書き込む
 * @param File
 * @throws Exception
 */
 public static void writeEncrycptFile(File infile, File outFile) throws Exception{
 IvParameterSpec ivSpec = new IvParameterSpec(EncryptConst.IV.getBytes(EncryptConst.CHAR_SET_UTF8));
 Cipher cipher = Cipher.getInstance(EncryptConst.CIPHER_ALGORITHM, "SunJCE");
 cipher.init(Cipher.ENCRYPT_MODE, genKey(), ivSpec);
 FileInputStream cin = new FileInputStream(infile);
 CipherOutputStream fos = new CipherOutputStream(new FileOutputStream(outFile), cipher);
        byte[] buffer = new byte[8192];
        int read = cin.read(buffer);
        while(read != -1){
        	fos.write(buffer, 0, read);
            read = cin.read(buffer);
        }
        cin.close();
        fos.close();
 }


 /**
 * 二進数から十六進数に変換
 * @param buf
 * @return
 */
 private 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();
 }


 /**
 * 十六進数から二進数に変換
 * @param hexStr
 * @return
 */
 private 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;
 }
}

转载于:https://my.oschina.net/windyson/blog/280683

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值