Search in sources :

Example 1 with JSSSecureRandom

use of org.mozilla.jss.crypto.JSSSecureRandom in project jss by dogtagpki.

the class pkcs12 method main.

public static void main(String[] args) {
    try {
        // Read arguments
        if (args.length != 3) {
            System.out.println("Usage: PFX <dbdir> <infile> <outfile>");
            System.exit(-1);
        }
        // open input file for reading
        FileInputStream infile = null;
        try {
            infile = new FileInputStream(args[1]);
        } catch (FileNotFoundException f) {
            System.out.println("Cannot open file " + args[1] + " for reading: " + f.getMessage());
            return;
        }
        int certfile = 0;
        // initialize CryptoManager. This is necessary because there is
        // crypto involved with decoding a PKCS #12 file
        CryptoManager.initialize(args[0]);
        CryptoManager manager = CryptoManager.getInstance();
        // Decode the P12 file
        PFX.Template pfxt = new PFX.Template();
        PFX pfx;
        try (BufferedInputStream is = new BufferedInputStream(infile, 2048)) {
            pfx = (PFX) pfxt.decode(is);
        }
        System.out.println("Decoded PFX");
        // print out information about the top-level PFX structure
        System.out.println("Version: " + pfx.getVersion());
        AuthenticatedSafes authSafes = pfx.getAuthSafes();
        SEQUENCE safeContentsSequence = authSafes.getSequence();
        System.out.println("AuthSafes has " + safeContentsSequence.size() + " SafeContents");
        // Get the password for the old file
        System.out.println("Enter password: ");
        Password pass = Password.readPasswordFromConsole();
        // get new password, which will be used for the new file we create
        // later
        System.out.println("Enter new password:");
        Password newPass = Password.readPasswordFromConsole();
        // Verify the MAC on the PFX.  This is important to be sure
        // it hasn't been tampered with.
        StringBuffer sb = new StringBuffer();
        if (pfx.verifyAuthSafes(pass, sb)) {
            System.out.println("AuthSafes verifies correctly.");
        } else {
            System.out.println("AuthSafes failed to verify because: " + sb);
        }
        // Create a new AuthenticatedSafes. As we read the contents of the
        // old authSafes, we will store them into the new one.  After we have
        // cycled through all the contents, they will all have been copied into
        // the new authSafes.
        AuthenticatedSafes newAuthSafes = new AuthenticatedSafes();
        // for(int i=0; i < asSeq.size(); i++) {
        for (int i = 0; i < safeContentsSequence.size(); i++) {
            // The safeContents may or may not be encrypted.  We always send
            // the password in.  It will get used if it is needed.  If the
            // decryption of the safeContents fails for some reason (like
            // a bad password), then this method will throw an exception
            SEQUENCE safeContents = authSafes.getSafeContentsAt(pass, i);
            System.out.println("\n\nSafeContents #" + i + " has " + safeContents.size() + " bags");
            // Go through all the bags in this SafeContents
            for (int j = 0; j < safeContents.size(); j++) {
                SafeBag safeBag = (SafeBag) safeContents.elementAt(j);
                // The type of the bag is an OID
                System.out.println("\nBag " + j + " has type " + safeBag.getBagType());
                // look for bag attributes
                SET attribs = safeBag.getBagAttributes();
                if (attribs == null) {
                    System.out.println("Bag has no attributes");
                } else {
                    for (int b = 0; b < attribs.size(); b++) {
                        Attribute a = (Attribute) attribs.elementAt(b);
                        if (a.getType().equals(SafeBag.FRIENDLY_NAME)) {
                            // the friendly name attribute is a nickname
                            BMPString bs = (BMPString) ((ANY) a.getValues().elementAt(0)).decodeWith(BMPString.getTemplate());
                            System.out.println("Friendly Name: " + bs);
                        } else if (a.getType().equals(SafeBag.LOCAL_KEY_ID)) {
                            // the local key id is used to match a key
                            // to its cert.  The key id is the SHA-1 hash of
                            // the DER-encoded cert.
                            OCTET_STRING os = (OCTET_STRING) ((ANY) a.getValues().elementAt(0)).decodeWith(OCTET_STRING.getTemplate());
                            System.out.println("LocalKeyID:");
                        /*
                            AuthenticatedSafes.
                                print_byte_array(os.toByteArray());
							*/
                        } else {
                            System.out.println("Unknown attribute type: " + a.getType().toString());
                        }
                    }
                }
                // now look at the contents of the bag
                ASN1Value val = safeBag.getInterpretedBagContent();
                if (val instanceof PrivateKeyInfo) {
                    // A PrivateKeyInfo contains an unencrypted private key
                    System.out.println("content is PrivateKeyInfo");
                } else if (val instanceof EncryptedPrivateKeyInfo) {
                    // An EncryptedPrivateKeyInfo is, well, an encrypted
                    // PrivateKeyInfo. Usually, strong crypto is used in
                    // an EncryptedPrivateKeyInfo.
                    EncryptedPrivateKeyInfo epki = ((EncryptedPrivateKeyInfo) val);
                    System.out.println("content is EncryptedPrivateKeyInfo, algoid:" + epki.getEncryptionAlgorithm().getOID());
                    // Because we are in a PKCS #12 file, the passwords are
                    // char-to-byte converted in a special way.  We have to
                    // use the special converter class instead of the default.
                    PrivateKeyInfo pki = epki.decrypt(pass, new org.mozilla.jss.pkcs12.PasswordConverter());
                    // import the key into the key3.db
                    CryptoToken tok = manager.getTokenByName("Internal Key Storage Token");
                    CryptoStore store = tok.getCryptoStore();
                    tok.login(new ConsolePasswordCallback());
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    pki.encode(baos);
                    store.importPrivateKey(baos.toByteArray(), PrivateKey.RSA);
                    // re-encrypt the PrivateKeyInfo with the new password
                    // and random salt
                    byte[] salt = new byte[PBEAlgorithm.PBE_SHA1_DES3_CBC.getSaltLength()];
                    JSSSecureRandom rand = CryptoManager.getInstance().getSecureRNG();
                    rand.nextBytes(salt);
                    epki = EncryptedPrivateKeyInfo.createPBE(PBEAlgorithm.PBE_SHA1_DES3_CBC, newPass, salt, 1, new PasswordConverter(), pki);
                    // Overwrite the previous EncryptedPrivateKeyInfo with
                    // this new one we just created using the new password.
                    // This is what will get put in the new PKCS #12 file
                    // we are creating.
                    safeContents.insertElementAt(new SafeBag(safeBag.getBagType(), epki, safeBag.getBagAttributes()), i);
                    safeContents.removeElementAt(i + 1);
                } else if (val instanceof CertBag) {
                    System.out.println("content is CertBag");
                    CertBag cb = (CertBag) val;
                    if (cb.getCertType().equals(CertBag.X509_CERT_TYPE)) {
                        // this is an X.509 certificate
                        OCTET_STRING os = (OCTET_STRING) cb.getInterpretedCert();
                        Certificate cert = (Certificate) ASN1Util.decode(Certificate.getTemplate(), os.toByteArray());
                        cert.getInfo().print(System.out);
                    } else {
                        System.out.println("Unrecognized cert type");
                    }
                } else {
                    System.out.println("content is ANY");
                }
            }
            // Add the new safe contents to the new authsafes
            if (authSafes.safeContentsIsEncrypted(i)) {
                newAuthSafes.addEncryptedSafeContents(AuthenticatedSafes.DEFAULT_KEY_GEN_ALG, newPass, null, AuthenticatedSafes.DEFAULT_ITERATIONS, safeContents);
            } else {
                newAuthSafes.addSafeContents(safeContents);
            }
        }
        // Create new PFX from the new authsafes
        PFX newPfx = new PFX(newAuthSafes);
        // Add a MAC to the new PFX
        newPfx.computeMacData(newPass, null, PFX.DEFAULT_ITERATIONS);
        // write the new PFX out to a file
        FileOutputStream fos = new FileOutputStream(args[2]);
        newPfx.encode(fos);
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : SET(org.mozilla.jss.asn1.SET) Attribute(org.mozilla.jss.pkix.primitive.Attribute) JSSSecureRandom(org.mozilla.jss.crypto.JSSSecureRandom) FileNotFoundException(java.io.FileNotFoundException) CryptoManager(org.mozilla.jss.CryptoManager) ANY(org.mozilla.jss.asn1.ANY) ASN1Value(org.mozilla.jss.asn1.ASN1Value) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) BufferedInputStream(java.io.BufferedInputStream) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) ConsolePasswordCallback(org.mozilla.jss.util.ConsolePasswordCallback) BMPString(org.mozilla.jss.asn1.BMPString) Password(org.mozilla.jss.util.Password) PFX(org.mozilla.jss.pkcs12.PFX) CryptoToken(org.mozilla.jss.crypto.CryptoToken) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SafeBag(org.mozilla.jss.pkcs12.SafeBag) FileInputStream(java.io.FileInputStream) FileNotFoundException(java.io.FileNotFoundException) AuthenticatedSafes(org.mozilla.jss.pkcs12.AuthenticatedSafes) CryptoStore(org.mozilla.jss.crypto.CryptoStore) CertBag(org.mozilla.jss.pkcs12.CertBag) FileOutputStream(java.io.FileOutputStream) EncryptedPrivateKeyInfo(org.mozilla.jss.pkix.primitive.EncryptedPrivateKeyInfo) PasswordConverter(org.mozilla.jss.pkcs12.PasswordConverter) EncryptedPrivateKeyInfo(org.mozilla.jss.pkix.primitive.EncryptedPrivateKeyInfo) PrivateKeyInfo(org.mozilla.jss.pkix.primitive.PrivateKeyInfo) Certificate(org.mozilla.jss.pkix.cert.Certificate)

Example 2 with JSSSecureRandom

use of org.mozilla.jss.crypto.JSSSecureRandom in project jss by dogtagpki.

the class PFX method main.

public static void main(String[] args) {
    try {
        if (args.length != 2) {
            System.out.println("Usage: PFX <dbdir> <infile>");
            System.exit(-1);
        }
        int certfile = 0;
        CryptoManager.initialize(args[0]);
        // Decode the P12 file
        PFX.Template pfxt = new PFX.Template();
        PFX pfx;
        FileInputStream fis = new FileInputStream(args[1]);
        try (BufferedInputStream in = new BufferedInputStream(fis, 2048)) {
            pfx = (PFX) pfxt.decode(in);
        }
        System.out.println("Decoded PFX");
        // now peruse it for interesting info
        System.out.println("Version: " + pfx.getVersion());
        AuthenticatedSafes authSafes = pfx.getAuthSafes();
        SEQUENCE asSeq = authSafes.getSequence();
        System.out.println("AuthSafes has " + asSeq.size() + " SafeContents");
        System.out.println("Enter password: ");
        Password pass = Password.readPasswordFromConsole();
        // get new password
        System.out.println("Enter new password:");
        Password newPass = Password.readPasswordFromConsole();
        // verify the PFX
        StringBuffer sb = new StringBuffer();
        if (pfx.verifyAuthSafes(pass, sb)) {
            System.out.println("AuthSafes verifies correctly");
        } else {
            System.out.println("AuthSafes failed to verify because: " + sb);
        }
        // get new AuthSafes ready
        AuthenticatedSafes newAuthSafes = new AuthenticatedSafes();
        for (int i = 0; i < asSeq.size(); i++) {
            SEQUENCE safeContents = authSafes.getSafeContentsAt(pass, i);
            System.out.println("\n\nSafeContents #" + i + " has " + safeContents.size() + " bags");
            for (int j = 0; j < safeContents.size(); j++) {
                SafeBag safeBag = (SafeBag) safeContents.elementAt(j);
                System.out.println("\nBag " + j + " has type " + safeBag.getBagType());
                SET attribs = safeBag.getBagAttributes();
                if (attribs == null) {
                    System.out.println("Bag has no attributes");
                } else {
                    for (int b = 0; b < attribs.size(); b++) {
                        Attribute a = (Attribute) attribs.elementAt(b);
                        if (a.getType().equals(SafeBag.FRIENDLY_NAME)) {
                            BMPString bs = (BMPString) ((ANY) a.getValues().elementAt(0)).decodeWith(BMPString.getTemplate());
                            System.out.println("Friendly Name: " + bs);
                        } else if (a.getType().equals(SafeBag.LOCAL_KEY_ID)) {
                            OCTET_STRING os = (OCTET_STRING) ((ANY) a.getValues().elementAt(0)).decodeWith(OCTET_STRING.getTemplate());
                            System.out.println("LocalKeyID:");
                            AuthenticatedSafes.print_byte_array(os.toByteArray());
                        } else {
                            System.out.println("Unknown attribute type");
                        }
                    }
                }
                ASN1Value val = safeBag.getInterpretedBagContent();
                if (val instanceof PrivateKeyInfo) {
                    System.out.println("content is PrivateKeyInfo");
                } else if (val instanceof EncryptedPrivateKeyInfo) {
                    EncryptedPrivateKeyInfo epki = ((EncryptedPrivateKeyInfo) val);
                    System.out.println("content is EncryptedPrivateKeyInfo, algoid:" + epki.getEncryptionAlgorithm().getOID());
                    PrivateKeyInfo pki = epki.decrypt(pass, new PasswordConverter());
                    byte[] salt = new byte[20];
                    JSSSecureRandom rand = CryptoManager.getInstance().getSecureRNG();
                    rand.nextBytes(salt);
                    epki = EncryptedPrivateKeyInfo.createPBE(PBEAlgorithm.PBE_SHA1_DES3_CBC, newPass, salt, 1, new PasswordConverter(), pki);
                    // replace the old safe bag with the new
                    safeContents.insertElementAt(new SafeBag(safeBag.getBagType(), epki, safeBag.getBagAttributes()), j);
                    safeContents.removeElementAt(j + 1);
                } else if (val instanceof CertBag) {
                    System.out.println("   content is CertBag");
                    CertBag cb = (CertBag) val;
                    if (cb.getCertType().equals(CertBag.X509_CERT_TYPE)) {
                        OCTET_STRING os = (OCTET_STRING) cb.getInterpretedCert();
                        FileOutputStream fos = new FileOutputStream("cert" + (certfile++) + ".der");
                        os.encode(fos);
                        fos.close();
                        Certificate cert = (Certificate) ASN1Util.decode(Certificate.getTemplate(), os.toByteArray());
                        cert.getInfo().print(System.out);
                    } else {
                        System.out.println("Unrecognized cert type");
                    }
                } else {
                    System.out.println("content is ANY");
                }
            }
            // Add the new safe contents to the authsafes
            if (authSafes.safeContentsIsEncrypted(i)) {
                newAuthSafes.addEncryptedSafeContents(AuthenticatedSafes.DEFAULT_KEY_GEN_ALG, newPass, null, AuthenticatedSafes.DEFAULT_ITERATIONS, safeContents);
            } else {
                newAuthSafes.addSafeContents(safeContents);
            }
        }
        // Create new PFX from new authsafes
        PFX newPfx = new PFX(newAuthSafes);
        newPfx.computeMacData(newPass, null, DEFAULT_ITERATIONS);
        FileOutputStream fos = new FileOutputStream("newjss.p12");
        newPfx.encode(fos);
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : SET(org.mozilla.jss.asn1.SET) Attribute(org.mozilla.jss.pkix.primitive.Attribute) JSSSecureRandom(org.mozilla.jss.crypto.JSSSecureRandom) ANY(org.mozilla.jss.asn1.ANY) ASN1Template(org.mozilla.jss.asn1.ASN1Template) ASN1Value(org.mozilla.jss.asn1.ASN1Value) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) BufferedInputStream(java.io.BufferedInputStream) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) BMPString(org.mozilla.jss.asn1.BMPString) Password(org.mozilla.jss.util.Password) FileInputStream(java.io.FileInputStream) InvalidBERException(org.mozilla.jss.asn1.InvalidBERException) DigestException(java.security.DigestException) IOException(java.io.IOException) CharConversionException(java.io.CharConversionException) TokenException(org.mozilla.jss.crypto.TokenException) NotInitializedException(org.mozilla.jss.NotInitializedException) FileOutputStream(java.io.FileOutputStream) EncryptedPrivateKeyInfo(org.mozilla.jss.pkix.primitive.EncryptedPrivateKeyInfo) EncryptedPrivateKeyInfo(org.mozilla.jss.pkix.primitive.EncryptedPrivateKeyInfo) PrivateKeyInfo(org.mozilla.jss.pkix.primitive.PrivateKeyInfo) Certificate(org.mozilla.jss.pkix.cert.Certificate)

Example 3 with JSSSecureRandom

use of org.mozilla.jss.crypto.JSSSecureRandom in project jss by dogtagpki.

the class SafeBag method createEncryptedPrivateKeyBag.

/**
 * Creates a SafeBag containing a PKCS-8ShroudedKeyBag, which is
 * an EncryptedPrivateKeyInfo. The key will be encrypted using
 *  a triple-DES PBE algorithm, using the supplied password.
 *
 * @param privk The PrivateKeyInfo containing the private key.
 * @param friendlyName The nickname for the key; should be the same
 *      as the nickname of the associated cert.
 * @param localKeyID The localKeyID for the key; should be the same as
 *      the localKeyID of the associated cert.
 * @param password The password used to encrypt the private key.
 */
public static SafeBag createEncryptedPrivateKeyBag(PrivateKeyInfo privk, String friendlyName, byte[] localKeyID, Password password) throws NotInitializedException, TokenException {
    try {
        PBEAlgorithm pbeAlg = PBEAlgorithm.PBE_SHA1_DES3_CBC;
        final int DEFAULT_ITERATIONS = 1;
        byte[] salt = new byte[pbeAlg.getSaltLength()];
        JSSSecureRandom rand = CryptoManager.getInstance().getSecureRNG();
        rand.nextBytes(salt);
        EncryptedPrivateKeyInfo epki = EncryptedPrivateKeyInfo.createPBE(PBEAlgorithm.PBE_SHA1_DES3_CBC, password, salt, DEFAULT_ITERATIONS, new PasswordConverter(), privk);
        SET attributes = new SET();
        attributes.addElement(new Attribute(FRIENDLY_NAME, new BMPString(friendlyName)));
        attributes.addElement(new Attribute(LOCAL_KEY_ID, new OCTET_STRING(localKeyID)));
        return new SafeBag(PKCS8_SHROUDED_KEY_BAG, epki, attributes);
    } catch (java.security.NoSuchAlgorithmException e) {
        throw new AssertionException("Unable to find PBE algorithm: " + e);
    } catch (java.security.InvalidKeyException e) {
        throw new AssertionException("InvalidKeyException while creating EncryptedContentInfo: " + e);
    } catch (java.security.InvalidAlgorithmParameterException e) {
        throw new AssertionException("InvalidAlgorithmParameterException while creating" + " EncryptedContentInfo: " + e);
    } catch (java.io.CharConversionException e) {
        throw new AssertionException("CharConversionException while creating EncryptedContentInfo: " + e);
    }
}
Also used : SET(org.mozilla.jss.asn1.SET) Attribute(org.mozilla.jss.pkix.primitive.Attribute) JSSSecureRandom(org.mozilla.jss.crypto.JSSSecureRandom) AssertionException(org.mozilla.jss.util.AssertionException) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) PBEAlgorithm(org.mozilla.jss.crypto.PBEAlgorithm) CharConversionException(java.io.CharConversionException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) EncryptedPrivateKeyInfo(org.mozilla.jss.pkix.primitive.EncryptedPrivateKeyInfo) BMPString(org.mozilla.jss.asn1.BMPString)

Example 4 with JSSSecureRandom

use of org.mozilla.jss.crypto.JSSSecureRandom in project jss by dogtagpki.

the class AuthenticatedSafes method addEncryptedSafeContents.

/**
 * Encrypts a SafeContents and adds it to the AuthenticatedSafes.
 *
 * @param keyGenAlg The algorithm used to generate a key from the password.
 *      Must be a PBE algorithm. <code>DEFAULT_KEY_GEN_ALG</code> is
 *      usually fine here. It only provides 40-bit security, but if the
 *      private key material is packaged in its own
 *      <i>EncryptedPrivateKeyInfo</i>, the security of the SafeContents
 *      is not as important.
 * @param password The password to use to generate the encryption key
 *      and IV.
 * @param salt The salt to use to generate the key and IV. If null is
 *      passed in, the salt will be generated randomly, which is usually
 *      the right thing to do.
 * @param iterationCount The number of hash iterations to perform when
 *      generating the key and IV.  Use DEFAULT_ITERATIONS unless
 *      you want to be clever.
 * @param safeContents A SafeContents, which is a SEQUENCE of SafeBags.
 *      Each element of the sequence must in fact be an instance of
 *      <code>SafeBag</code>.
 */
public void addEncryptedSafeContents(PBEAlgorithm keyGenAlg, Password password, byte[] salt, int iterationCount, SEQUENCE safeContents) throws NotInitializedException, InvalidKeyException, InvalidAlgorithmParameterException, TokenException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
    try {
        // generate salt if necessary
        if (salt == null) {
            // generate random salt
            JSSSecureRandom rand = CryptoManager.getInstance().createPseudoRandomNumberGenerator();
            salt = new byte[SALT_LENGTH];
            rand.nextBytes(salt);
        }
        EncryptedContentInfo encCI = EncryptedContentInfo.createPBE(keyGenAlg, password, salt, iterationCount, new PasswordConverter(), ASN1Util.encode(safeContents));
        EncryptedData encData = new EncryptedData(encCI);
        ContentInfo ci = new ContentInfo(encData);
        sequence.addElement(ci);
    } catch (CharConversionException e) {
        throw new RuntimeException("Unable to convert password: " + e.getMessage(), e);
    }
}
Also used : ContentInfo(org.mozilla.jss.pkcs7.ContentInfo) EncryptedContentInfo(org.mozilla.jss.pkcs7.EncryptedContentInfo) JSSSecureRandom(org.mozilla.jss.crypto.JSSSecureRandom) EncryptedData(org.mozilla.jss.pkcs7.EncryptedData) CharConversionException(java.io.CharConversionException) EncryptedContentInfo(org.mozilla.jss.pkcs7.EncryptedContentInfo)

Aggregations

JSSSecureRandom (org.mozilla.jss.crypto.JSSSecureRandom)4 CharConversionException (java.io.CharConversionException)3 BMPString (org.mozilla.jss.asn1.BMPString)3 OCTET_STRING (org.mozilla.jss.asn1.OCTET_STRING)3 SET (org.mozilla.jss.asn1.SET)3 Attribute (org.mozilla.jss.pkix.primitive.Attribute)3 EncryptedPrivateKeyInfo (org.mozilla.jss.pkix.primitive.EncryptedPrivateKeyInfo)3 BufferedInputStream (java.io.BufferedInputStream)2 FileInputStream (java.io.FileInputStream)2 FileOutputStream (java.io.FileOutputStream)2 ANY (org.mozilla.jss.asn1.ANY)2 ASN1Value (org.mozilla.jss.asn1.ASN1Value)2 SEQUENCE (org.mozilla.jss.asn1.SEQUENCE)2 Certificate (org.mozilla.jss.pkix.cert.Certificate)2 PrivateKeyInfo (org.mozilla.jss.pkix.primitive.PrivateKeyInfo)2 Password (org.mozilla.jss.util.Password)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 DigestException (java.security.DigestException)1