Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

java.security.KeyStoreException: Cannot store non-PrivateKeys

843811Jun 12 2005 — edited Feb 14 2006
I have been getting this exception:

Exception in thread "main" java.security.KeyStoreException: Cannot store non-PrivateKeys
at sun.security.provider.JavaKeyStore.engineSetKeyEntry(Unknown Source)
at java.security.KeyStore.setKeyEntry(Unknown Source)
at KeyStoreExample.encrypt(KeyStoreExample.java:89)
at KeyStoreExample.main(KeyStoreExample.java:39)


while running this code:
private static void encrypt(char[] password, String plaintext)
  throws Exception
  {
    System.out.println("Generating a TripleDES key...");

    // Create a Blowfish key
    KeyGenerator keyGenerator = KeyGenerator.getInstance("TripleDES");
    keyGenerator.init(168);
    Key key = keyGenerator.generateKey();

    System.out.println("Done generating the key.");

    // Create a cipher using that key to initialize it
    Cipher cipher = Cipher.getInstance("TripleDES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);

    byte[] plaintextBytes = plaintext.getBytes();

    // Perform the actual encryption
    byte[] cipherText = cipher.doFinal(plaintextBytes);

    // Now we need to Base64-encode it for ascii display
    BASE64Encoder encoder = new BASE64Encoder();
    String output = encoder.encode(cipherText);

    System.out.println("Ciphertext: "+output);

    /* Create a keystore and place the key in it
     * We're using a jceks keystore, which is provided by Sun's JCE.
     * If you don't have the JCE installed, you can use "JKS",
     * which is the default keystore. It doesn't provide
     * the same level of protection however.
     */
    KeyStore keyStore = KeyStore.getInstance("JKS", "SUN");

    // This initializes a blank keystore
    keyStore.load(null, null);

    // Now we add the key to the keystore, protected
    // by the password.
    keyStore.setKeyEntry("LuisTest", key, password, null);

    // Store the password to the filesystem, protected
    // by the same password.
    FileOutputStream fos = new FileOutputStream(FILENAME);
    keyStore.store(fos, password);
    fos.close();
The error fires when it gets to this line
    keyStore.setKeyEntry("LuisTest", key, password, null);
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 14 2006
Added on Jun 12 2005
9 comments
11,213 views