java aes key_Java AES KeyStore IvParameterSpec

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.security.InvalidAlgorithmParameterException;

import java.security.InvalidKeyException;

import java.security.KeyStore;

import java.security.KeyStore.PasswordProtection;

import java.security.KeyStore.SecretKeyEntry;

import java.security.KeyStoreException;

import java.security.NoSuchAlgorithmException;

import java.security.SecureRandom;

import java.security.UnrecoverableEntryException;

import java.security.cert.CertificateException;

import java.util.Base64;

import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.KeyGenerator;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.SecretKey;

import javax.crypto.spec.IvParameterSpec;

public class AESTest {

private static final String KEY_FILE = "C:/Users/wangdon/Downloads/rm-TEST.ks";

private static final String ALIAS = "RM-AES";

private static final String PASSWORD = "U09NRVRISU5HQllCQVNFNjRkd2FuZ0AxcWF6QFdTWDNlREMkUmZ2"; // It actually equal to KEY_STORE_PASSWORD. I use KEY_STORE_PASSWORD in this case because it seems more safe.

private static final byte[] KEY_STORE_PASSWORD = { 0x55, 0x30, 0x39, 0x4e, 0x52, 0x56, 0x52, 0x49, 0x53, 0x55, 0x35, 0x48, 0x51, 0x6c, 0x6c, 0x43, 0x51, 0x56, 0x4e, 0x46, 0x4e, 0x6a, 0x52, 0x6b, 0x64, 0x32, 0x46, 0x75, 0x5a, 0x30, 0x41, 0x78, 0x63, 0x57, 0x46, 0x36, 0x51, 0x46, 0x64, 0x54, 0x57, 0x44, 0x4e, 0x6c, 0x52, 0x45, 0x4d, 0x6b, 0x55, 0x6d, 0x5a, 0x32 };

private static final String ALGORITHM = "AES/CBC/PKCS5Padding";

/**

* It will create a new secret key and save it in key store file

*/

public static void saveSecretKey() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {

KeyGenerator kgen = KeyGenerator.getInstance("AES"); // By default JDK uses sunJCE provider

kgen.init(128, new SecureRandom()); // sunJCE can only support 128 bit length key. For 256 bit key, see Bouncy Castle provider

SecretKey secretKey = kgen.generateKey();

String tmp = Base64.getEncoder().encodeToString(secretKey.getEncoded());

System.out.println("The secretKey in base64 encoded is: " + tmp + ", with length=" + tmp.length());

KeyStore keyStore = KeyStore.getInstance("JCEKS");

keyStore.load(null, null); // Initialize it firstly

PasswordProtection keyPassword = new PasswordProtection(Base64.getEncoder().encodeToString(KEY_STORE_PASSWORD).toCharArray());

SecretKeyEntry keyStoreEntry = new SecretKeyEntry(secretKey); //JCEKS support SecretKeyEntry

keyStore.setEntry(ALIAS, keyStoreEntry, keyPassword);

keyStore.store(new FileOutputStream(KEY_FILE), new String(KEY_STORE_PASSWORD).toCharArray());

}

public static SecretKey loadSecretKey() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableEntryException {

KeyStore keyStore = KeyStore.getInstance("JCEKS");

keyStore.load(new FileInputStream(KEY_FILE), new String(KEY_STORE_PASSWORD).toCharArray());

PasswordProtection keyPassword = new PasswordProtection(Base64.getEncoder().encodeToString(KEY_STORE_PASSWORD).toCharArray());

SecretKey secretKey = ((SecretKeyEntry) keyStore.getEntry(ALIAS, keyPassword)).getSecretKey();

String tmp = Base64.getEncoder().encodeToString(secretKey.getEncoded());

System.out.println("The secretKey in base64 encoded is: " + tmp + ", with length=" + tmp.length());

return secretKey;

}

public static String encrypt(SecretKey key, String source) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

Cipher cipher = Cipher.getInstance(ALGORITHM);

IvParameterSpec ivSpec = new IvParameterSpec(key.getEncoded());

cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

byte[] encodedInByte = cipher.doFinal(source.getBytes());

String encodedInStr = Base64.getEncoder().encodeToString(encodedInByte);

System.out.println("\"" + source + "\" is encryped in base64 encoded is: " + encodedInStr);

return encodedInStr;

}

public static String decrypt(SecretKey key, String encoded) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

Cipher cipher = Cipher.getInstance(ALGORITHM);

IvParameterSpec ivSpec = new IvParameterSpec(key.getEncoded());

cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);

byte[] encodedInByte = Base64.getDecoder().decode(encoded);

encodedInByte = cipher.doFinal(encodedInByte);

String source = new String(encodedInByte);

System.out.println("Decoded to " + source);

return source;

}

public static void main(String[] args) throws Exception {

saveSecretKey();

SecretKey aesKey = loadSecretKey();

String source = "ABCD";

String encoded = encrypt(aesKey, source);

decrypt(aesKey, encoded);

}

}

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2015-09-16 18:54

浏览 1331

评论

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值