2009-11-29 5 views
0

Ceci a été demandé deux ou trois fois, mais aucun cas fournir des tests codés. Ici, je donne un exemple du problème:Java: Format invalide keystore, lorsque le code généré par

  1. génération programmatique d'un Keystore (travaux)
  2. création de certificat dans ce magasin (œuvres)
  3. sauver keystore sur le disque (travaux)
  4. liste keystore avec keytool (travaux)
  5. chargement du programme keystore (échoue avec IOException: InvalidKeystoreFormat)

Qu'est-ce que je ne g et que dans les deux enregistrer et charger, j'utilise KeyStore.getInstance (« JKS »), mais son échec. Toutes suggestions sont les bienvenues!

Sortie Durée:

 
Creating private keystore at 'private.keystore'. 
Created keystore, now created signer cert 
Created signer cert, saving cert 
Reloading keystore: 
Failed to load the keystore after creation: Invalid keystore format 

test case Source:

 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.security.InvalidKeyException; 
import java.security.KeyStore; 
import java.security.KeyStoreException; 
import java.security.NoSuchAlgorithmException; 
import java.security.NoSuchProviderException; 
import java.security.PrivateKey; 
import java.security.SignatureException; 
import java.security.cert.Certificate; 
import java.security.cert.CertificateException; 
import java.security.cert.X509Certificate; 

import sun.security.x509.X500Name; 

public class KeystoreCreator 
{ 
private String fPrivateKeyStore; 
private String fPrivateKeyStorePassword; 
private String fPrivateKeyStoreKeyPassword; 
private String fPublicKeyCipherPassword; 
private String fPrivateKeyAlias; 

/** 
    * @param args 
    * @throws Exception 
    */ 
public static void main(String[] args) throws Exception 
{ 
    KeystoreCreator creator = new KeystoreCreator(); 

    creator.setPrivateKeyStore("private.keystore"); 
    creator.setPrivateKeyStorePassword("beer123"); 

    creator.setPrivateKeyAlias("myalias"); 
    creator.setPrivateKeyStoreKeyPassword("beer123"); 
    creator.setPublicKeyCipherPassword("beer123"); 

    creator.initKeyStores(); 
} 

public KeystoreCreator() 
{ 
} 

public void setPrivateKeyStore(String name) 
{ 
    fPrivateKeyStore=name; 
} 
public void setPrivateKeyStorePassword(String pass) 
{ 
    fPrivateKeyStorePassword=pass; 
} 
public void setPrivateKeyStoreKeyPassword(String pass) 
{ 
    fPrivateKeyStoreKeyPassword=pass; 
} 
public void setPublicKeyCipherPassword(String pass) 
{ 
    fPublicKeyCipherPassword=pass; 
} 
public void setPrivateKeyAlias(String alias) 
{ 
    fPrivateKeyAlias=alias; 
} 

    public void initKeyStores() throws Exception 
    { 
     OutputStream out = null; 
     File f=new File(fPrivateKeyStore); 
     if (f.exists()) 
     { 
     f.delete(); 
     if (f.exists()) 
     { 
      throw new IOException("Want to remove the keystore but can't, still reported as present after removal"); 
     } 
     } 
     try 
     { 
     System.out.println("Creating private keystore at '" + fPrivateKeyStore + "'."); 
     out = new FileOutputStream(fPrivateKeyStore); 
     KeyStore privateKeyStore = KeyStore.getInstance("JKS"); 
     privateKeyStore.load(null, fPrivateKeyStorePassword.toCharArray()); 

     System.out.println("Created keystore, now created signer cert"); 
     X500Name x500name=getCA(); 
     Certificate cert = createCertificate(fPrivateKeyAlias, fPrivateKeyStoreKeyPassword, x500name, privateKeyStore); 

     System.out.println("Created signer cert, saving cert"); 
     privateKeyStore.store(out, fPublicKeyCipherPassword.toCharArray()); 
     out.flush(); 
     out.close(); 
     //try to load it. 
     KeyStore reloadedKeyStore = KeyStore.getInstance("JKS"); 
     try 
     { 
      InputStream reloadedIs=getClass().getClassLoader().getResourceAsStream(fPrivateKeyStore); 
      if (reloadedIs!=null) 
      { 
      System.out.println("Reloading keystore:"); 
      reloadedKeyStore.load(reloadedIs, fPrivateKeyStorePassword.toCharArray()); 
      } 
     } 
     catch (Exception e) 
     { 
      System.err.println("Failed to load the keystore after creation: "+e.getLocalizedMessage()); 
     } 
     } 
     catch (Exception e) 
     { 
     System.err.println("Failed to save the keystore: "+e.getLocalizedMessage()); 
     } 
    } 

    private X500Name getCA() throws IOException 
    { 
    return new sun.security.x509.X500Name("a","b", "c","d","e", "GB"); 
    } 

    public Certificate createCertificate(String alias, String keyPassword, 
      sun.security.x509.X500Name x500Name, KeyStore keyStore) throws NoSuchAlgorithmException, 
      InvalidKeyException, CertificateException, SignatureException, NoSuchProviderException, 
      KeyStoreException {  
     sun.security.x509.CertAndKeyGen keypair = new sun.security.x509.CertAndKeyGen("RSA", "MD5WithRSA"); 
     keypair.generate(1024); 
     PrivateKey privKey = keypair.getPrivateKey(); 
     X509Certificate[] chain = new X509Certificate[1]; 
     chain[0] = keypair.getSelfCertificate(x500Name, 7000 * 24 * 60 * 60); 
     keyStore.setKeyEntry(alias, privKey, keyPassword.toCharArray(), chain); 

     Certificate cert = keyStore.getCertificate(alias); 
     return cert; 
    } 
} 

Répondre

2

1) Vous créez la clé privée stockée dans le répertoire de travail courant, par écrit à un fichier: new FileOutputStream(fPrivateKeyStore);

2) Plus tard, vous lu à partir du chemin de classe en utilisant getClass().getClassLoader().getResourceAsStream(fPrivateKeyStore);

Je pense que vous lisez les mauvais fichiers. Et il y en a déjà un autre avec le nom private.keystore des tests précédents. Pour vérifier, vous pouvez imprimer le chemin de fichier absolu des deux fichiers, par ex. new File(fPrivateKeyStore).getAbsolutePath() et le comparer à getClass().getClassLoader().getResource(fPrivateKeyStore).toFileURL();

+0

OMG, comment ai-je pu rater ça. Merci, tout va bien maintenant. – javahollic

0

je manquer quelque chose, mais pourquoi ne pas simplement re-charger la clé privée stockée à l'aide FileInputStream?

InputStream reloadedIs = new FileInputStream(fPrivateKeyStore); 

(je ne suis pas certain cela résout le problème, je viens de remarquer tout en balayant votre code)

Questions connexes