我正在使用Java API创建一个密钥存储库文件,即相当于Java命令
keytool -genseckey -alias some.alias -keyalg AES -keysize 128 -keypass <an encrypted byte string> -storetype JCEKS -keystore <filename> –storepass <some_pwd>
代码:…
key=get128MD5(strToHash);
System.out.println(String.format("Hashing value : '%s' ", Hex.toHexString(key)));
try {
KeyStore.ProtectionParameter protParam =
new KeyStore.PasswordProtection("XXXXX".toCharArray ());
javax.crypto.SecretKey mySecretKey=new SecretKeySpec(key,"AES");
KeyStore.SecretKeyEntry skEntry =
new KeyStore.SecretKeyEntry(mySecretKey);
ks.setEntry(alias, skEntry, protParam);
try (FileOutputStream fos = new FileOutputStream("filename")) {
ks.store(fos, "XXXXX".toCharArray ());
fos.close();
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
} catch (KeyStoreException e1) {
...
above error happens when trying to load from keystore file :
public static Key getKey(String keyalias,byte[] keypassbyte) throws KeyStoreException {
Key key = null;
try{
if(ks!=null){
log.info("Getting key from Keystore.");
key =ks.getKey(keyalias, Hex.toHexString(keypassbyte).toCharArray());
}
if(key==null){
throw new KeyStoreException("Failed to get secret key entry.");
}
}catch (NoSuchAlgorithmException nsae) {
throw new KeyStoreException("Algorithm for recovering the secret key cannot be found." + nsae.getMessage());
` }catch (UnrecoverableEntryException uee) {
throw new KeyStoreException("Invalid entry password to recover secret." + uee.getMessage());
}catch (KeyStoreException kse) {
throw new KeyStoreException("Failed to get secret key entry." + kse.getMessage());
}catch(NullPointerException ex){
throw new NullPointerException("NullPointerException " + ex.getMessage());
} catch (RuntimeException e) {
throw new RuntimeException("Failed to get secret key."+ e.getMessage());
}
return key;
你知道哪里出了问题吗?我尝试了"ks"的不同变体。setKey方法和包含长度参数,这没有帮助。我使用WIN10和Eclipse/Java 1.8
感谢key =ks.getKey(keyalias,
Hex.toHexString(keypassbyte).toCharArray())
试图使用十六进制形式的密码?为什么?只需使用与创建密钥时相同的方法