How to destroy Java PrivateKey

The default PrivateKey.destroy() may not be implemented

private static void xor(byte[] p, byte[] key) {
for (int i=0; i < p.length; i++) {
p[i] = (byte)(p[i] ^ key[i % key.length]);
}
}

public final static void main(String[] args) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(4096);
KeyPair kp = keyPairGenerator.generateKeyPair();
byte[] encKey = kp.getPrivate().getEncoded();
byte[] text = "This is a sample text!".getBytes();
xor(text, encKey);
PrivateKey pk = kp.getPrivate();
try {
pk.destroy();
}
catch (Exception e) {
Field keyField = sun.security.pkcs.PKCS8Key.class.getDeclaredField("key");
keyField.setAccessible(true);
keyField.set(pk, new byte[] { 0 });
Field encodedField = sun.security.pkcs.PKCS8Key.class.getDeclaredField("encodedKey");
encodedField.setAccessible(true);
encodedField.set(pk, null);
RSAPrivateKey asRsa = (RSAPrivateKey) pk;
clear(asRsa.getModulus());
clear(asRsa.getPrivateExponent());
}
xor(text, pk.getEncoded());
System.out.println(new String(text));
}

private static void clear(BigInteger bigInt) throws Exception {
Field valField = bigInt.getClass().getDeclaredField("mag");
valField.setAccessible(true);
valField.set(bigInt, new int[] { 0 });
}

The output is garbage: dê`1"hsl&zKë8ê’-udyq!

It means that we destroyed Private Key material properly.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Jakub Jóźwicki
Jakub Jóźwicki

No responses yet

Write a response