我真的很困惑为什么编码值不同
这是完整的代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyStore;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.bouncycastle.util.encoders.Base64;
public class KeyStoreDemo {
private static final String KEY_STORE_TYPE = "JCEKS";
private static final String KEY_STORE_NAME = "sampleKeyStore.store";
private static final String KEY_STORE_PASSWORD = "letmein";
public static void main(String[] args) throws Exception {
File storeFile = new File(KEY_STORE_NAME);
storeFile.createNewFile();
//Create a keystore
createKeyStore(KEY_STORE_TYPE, storeFile,KEY_STORE_PASSWORD);
//Generate a key and store it in keystore
KeyStore keyStore = loadKeyStore(KEY_STORE_TYPE,storeFile,KEY_STORE_PASSWORD);
// Get the KeyGenerator
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");keyGenerator.init(128); Key keytemp = keyGenerator.generateKey();
System.out.println("key- Base64 before:"+Base64.encode (keytemp.getEncoded()) );
//createSecretKeyAndStore( keyStore, keytemp, "samplekey" ,"samplepwd");
createSecretKeyAndStore(storeFile, keyStore, KEY_STORE_PASSWORD, keytemp, "samplekey" ,"samplepwd");
Key key = getKeyFromStore(keyStore, "samplekey", "samplepwd");
System.out.println("key- Base64 after :"+Base64.encode (key.getEncoded()) );
}
private static KeyStore createKeyStore(String keyStoreType,File keyStoreFile,String keyStorePassword) throws Exception{
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load((InputStream) null, keyStorePassword.toCharArray());
// Write KeyStore to disk
final FileOutputStream fileOutputStream = new FileOutputStream(keyStoreFile);
try {
keyStore.store(fileOutputStream, keyStorePassword.toCharArray());
fileOutputStream.flush();
} finally {
fileOutputStream.close();
}
return keyStore;
}
private static KeyStore loadKeyStore(String keyStoreType,File keyStoreFile,String keyStorePassword) throws Exception{
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load((InputStream) new FileInputStream(keyStoreFile), keyStorePassword.toCharArray());
return keyStore;
}
private static void createSecretKeyAndStore(File keyStorefile ,KeyStore keyStore,String keyStorePwd, Key key, String keyAlias ,String keyAccessPassword) throws Exception{
keyStore.setKeyEntry(keyAlias, key, keyAccessPassword.toCharArray(), null);
// Write KeyStore to disk
final FileOutputStream fileOutputStream = new FileOutputStream(keyStorefile);
try {
keyStore.store(fileOutputStream, keyStorePwd.toCharArray());
} finally {
fileOutputStream.close();
}
}
private static Key getKeyFromStore(KeyStore keyStore, String keyAlias,String keyAccessPassword) throws Exception {
Key keyFromStore = null;
keyFromStore = keyStore.getKey(keyAlias, keyAccessPassword.toCharArray());
return keyFromStore;
}
}
结果
key- Base64 before:[B@c7e553
key- Base64 after :[B@1ac04e8