Okay. So I've been searching google for days trying to find an answer to this question. I am trying to password protect private keys of a public/private keypair like keytool does. This needs to be used in an environment where keytool is not available and plus, I want to find out how keytool does it. Does anyone know how to do this in Java?
3 Answers
Use password based encryption - it is best for this purpose.
Keytool doesn't implement it itself. It is implemented in keystore. To be more precise in java.security.KeyStoreSpi#engineSetKeyEntry
and java.security.KeyStoreSpi#engineGetKey
methods.
Keystore type JKS is implemented in sun.security.provider.JavaKeyStore
. Password protection is implemented in sun.security.provider.KeyProtector
. JKS stores keys in PKCS#8 format, but uses its own algorithm (OID 1.3.6.1.4.1.42.2.17.1.1) with SHA1. It is a kind of PBE. Look at example of open JKS implementation.
As Tom suggested below (in his comment) you could look at sun.security.tools.KeyTool class.

- 8,750
- 3
- 36
- 60
-
1You could read [KeyTool.java](http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/tip/src/share/classes/sun/security/tools/KeyTool.java), and follow this from there. – Tom Anderson Jul 11 '11 at 22:11
-
@tom: Great shot. I added it into post. – zacheusz Jul 11 '11 at 22:17
-
Thanks (: It looks like I'm going to be using PBE. – James Jul 12 '11 at 12:41
Since you would need to reverse the stored password, there's usually an application specific encoding that gets applied.
e.g. in WebSphere, it's an xor-ed hash and a base64 encoding.
They usually have something like a stash file or some configuration file that stores the encoded password. (Not I don't use the word encrypt)
What this means is that the password cannot be readily glanced by someone inadvertently. However, someone who knows the encoding algorithm can easily decode it so that stash file or configuration file needs to be kept in a secure location.

- 35,625
- 19
- 175
- 265
-
Use of stash file is reversible (famous unstash.pl script), so xored passwords in WebSphere too. – zacheusz Jul 11 '11 at 20:55
Best bet: Use AES encryption with a salt. It is generally a good idea to use well tested technology rather than rolling your own when it comes to cryptography. Here's another post which whose answers should answer all of your questions: Java 256-bit AES Password-Based Encryption

- 1
- 1

- 8,061
- 5
- 50
- 73