[英]How do I clone a java keystore instance?
I would like to clone a java keystore instance. 我想克隆一个Java密钥库实例。
I wrote the master keystore to a ByteArrayOutputStream and flushed it to a byte array. 我将主密钥库写入ByteArrayOutputStream并将其刷新为字节数组。 I then created a new keystore instance and loaded from the byteArray as ByteArrayInputStream. 然后,我创建了一个新的密钥库实例,并从byteArray加载为ByteArrayInputStream。 It worked fine. 工作正常。 Just wondering if there is a better way to do it. 只是想知道是否有更好的方法可以做到这一点。
I couldn't find any examples of doing this. 我找不到执行此操作的任何示例。 In the event that I am doing it the right way, I thought posting it would at-least help someone who wants to do something similar. 如果我以正确的方式做事,我认为发布它至少可以帮助想要做类似事情的人。
public static void test() throws KeyStoreException, NoSuchAlgorithmException,
CertificateException, IOException, UnrecoverableKeyException
{
KeyStore originalKeyStore = KeyStore.getInstance( "JCEKS");
originalKeyStore.load( null, "1234".toCharArray());
Key originalKey = generateNewKey();
originalKeyStore.setKeyEntry( "keyAlias", originalKey, "1234".toCharArray(), null);
ByteArrayOutputStream os = new ByteArrayOutputStream();
originalKeyStore.store( os, "1234".toCharArray());
ByteArrayInputStream is = new ByteArrayInputStream( os.toByteArray());
KeyStore clonedKeyStore = KeyStore.getInstance( "JCEKS");
clonedKeyStore.load( is, "1234".toCharArray());
Key clonedKey = clonedKeyStore.getKey( "keyAlias", "1234".toCharArray());
String encodedOriginalKey = Base64.getEncoder().encodeToString( originalKey.getEncoded());
String encodedClonedKey = Base64.getEncoder().encodeToString( clonedKey.getEncoded());
System.out.println( "Original key:" + encodedOriginalKey);
System.out.println( "ClonedKey:" + encodedClonedKey);
System.out.println( "Key equality:" + encodedClonedKey.compareTo( encodedOriginalKey));
}
public static Key generateNewKey() throws NoSuchAlgorithmException
{
KeyGenerator kgen = KeyGenerator.getInstance( "AES");
kgen.init( 256, new SecureRandom());
return kgen.generateKey();
}
by deep clone you can make copy of almost everything. 通过深度克隆,您几乎可以复制所有内容。
deep copy code 深层复制代码
public static Object clone(Object o) {
try {
ByteArrayOutputStream BAOS = new ByteArrayOutputStream();
ObjectOutputStream OOS = new ObjectOutputStream(BAOS);
OOS.writeObject(o);
ByteArrayInputStream BAIS = new ByteArrayInputStream(BAOS.toByteArray());
ObjectInputStream OIS = new ObjectInputStream(BAIS);
return OIS.readObject();
} catch (Exception e) {e.printStackTrace(); return null;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.