Commit c33494c6 authored by Jamie Tanna's avatar Jamie Tanna

Document `SecretKey` extraction from Java keystore

Closes #629.
parent 764f55bb
Pipeline #74498475 passed with stages
in 5 minutes and 17 seconds
title: "Extract Secret Key Java Keystore"
description: "How to extract a symmetric `SecretKey` entry from a Java keystore."
- blogumentation
- java
- keystore
license_code: Apache-2.0
license_prose: CC-BY-NC-SA-4.0
date: 2019-08-02T23:43:03+0100
slug: "extract-secret-key-java-keystore"
Yesterday, I was trying to pull a shared secret (a `SecretKeyEntry` not a `PrivateKeyEntry`) out of a Java keystore.
I'd created it quite some time ago and annoyingly didn't have a copy of the secret stored anywhere. What I did have, however, was the `keystorepass` and the `keypass`, so wanted to pull the key out.
This was achievable using the below Java class:
import java.math.BigInteger;
import javax.crypto.SecretKey;
public class OutputSecretKey {
public static void main(String[] args) throws Exception {
final String fileName = args[0];
final String alias = args[1];
final char[] storepass = args[2].toCharArray();
final char[] keypass = args[3].toCharArray();
KeyStore ks = KeyStore.getInstance("JCEKS");
try (FileInputStream fis = new FileInputStream(fileName)) {
ks.load(fis, storepass);
SecretKey secretKey = (SecretKey) ks.getKey(alias, keypass);
String secretAsHex = new BigInteger(1, secretKey.getEncoded()).toString(16);
/* */
private static String hexToAscii(String hexStr) {
StringBuilder output = new StringBuilder("");
for (int i = 0; i < hexStr.length(); i += 2) {
String str = hexStr.substring(i, i + 2);
output.append((char) Integer.parseInt(str, 16));
return output.toString();
This can then be run as follows:
$ java
$ java OutputSecretKey keystore.jceks alias thisisthekeystorepass thekeyhasthispassword
Note that this code has been adapted from [_How to display Java keystore SecretKeyEntry from command line_]( and [_Convert Hex to ASCII in Java_](
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment