java aes key,在Java中使用密钥库存储AES密钥

I am using Java keystore to store the secret key for AES encryption.

final String strToEncrypt = "Hello World";

KeyGenerator kg = KeyGenerator.getInstance("AES");

kg.init(128);

SecretKey sk = kg.generateKey();

String secretKey = String.valueOf(Hex.encodeHex(sk.getEncoded()));

//Storing AES Secret key in keystore

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

char[] password = "keystorepassword".toCharArray();

java.io.FileInputStream fis = null;

try {

fis = new java.io.FileInputStream("keyStoreName");

ks.load(fis, password);

} finally {

if (fis != null) {

fis.close();

}

KeyStore.ProtectionParameter protParam =

new KeyStore.PasswordProtection(password);

KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(sk);

ks.setEntry("secretKeyAlias", skEntry, protParam);

But i am getting following Exception.

Exception in thread "main" java.security.KeyStoreException: Uninitialized keystore

at java.security.KeyStore.setEntry(Unknown Source)

How to fix this error? Thanks in advance

解决方案

According to the KeyStore documentation ,

Before a keystore can be accessed, it must be loaded.

so you are loading the KeyStore but what if a FileNotFoundException occures at

fis = new java.io.FileInputStream("keyStoreName"); , hence if file does not exist we load the KeyStore with null values ,like , ks.load(null,null); .

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值