Search in sources :

Example 1 with CertBag

use of org.mozilla.jss.pkcs12.CertBag 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 CertBag

use of org.mozilla.jss.pkcs12.CertBag in project jss by dogtagpki.

the class PKCS12Util method addCertBag.

public void addCertBag(PKCS12CertInfo certInfo, SEQUENCE safeContents) throws Exception {
    byte[] id = certInfo.getID();
    logger.debug(" - Certificate ID: " + Utils.HexEncode(id));
    X509CertImpl cert = certInfo.getCert();
    ASN1Value certAsn1 = new OCTET_STRING(cert.getEncoded());
    CertBag certBag = new CertBag(CertBag.X509_CERT_TYPE, certAsn1);
    SET certAttrs = createCertBagAttrs(certInfo);
    SafeBag safeBag = new SafeBag(SafeBag.CERT_BAG, certBag, certAttrs);
    safeContents.addElement(safeBag);
}
Also used : ASN1Value(org.mozilla.jss.asn1.ASN1Value) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) CertBag(org.mozilla.jss.pkcs12.CertBag) SET(org.mozilla.jss.asn1.SET) X509CertImpl(org.mozilla.jss.netscape.security.x509.X509CertImpl) SafeBag(org.mozilla.jss.pkcs12.SafeBag)

Example 3 with CertBag

use of org.mozilla.jss.pkcs12.CertBag in project SpringRemote by HaleyWang.

the class PKCS12KeyStore method processSafeContents.

private void processSafeContents(byte[] scBer) throws IOException {
    ByteArrayInputStream ba = new ByteArrayInputStream(scBer);
    SafeContents sc = new SafeContents();
    ASN1DER ber = new ASN1DER();
    ber.decode(ba, sc);
    for (int j = 0; j < sc.getCount(); j++) {
        SafeBag safeBag = sc.getSafeBag(j);
        String friendlyName = getAttribute(safeBag, "1.2.840.113549.1.9.20");
        String localKeyId = getAttribute(safeBag, "1.2.840.113549.1.9.21");
        if (friendlyName != null) {
            if (localKeyId != null) {
                name2id.put(friendlyName, localKeyId);
            }
            if (!aliases.contains(friendlyName)) {
                aliases.addElement(friendlyName);
            }
        } else if (localKeyId != null) {
            name2id.put(localKeyId, localKeyId);
            if (!aliases.contains(localKeyId)) {
                aliases.addElement(localKeyId);
            }
        }
        switch(safeBag.getBagType()) {
            case SafeBag.TYPE_PKCS8_SHROUDED_KEYBAG:
                EncryptedPrivateKeyInfo keyBag = (EncryptedPrivateKeyInfo) safeBag.bagValue.getValue();
                privateKeys.put(localKeyId, keyBag);
                break;
            case SafeBag.TYPE_CERTBAG:
                CertBag cb = (CertBag) safeBag.bagValue.getValue();
                byte[] derCert = ((ASN1OctetString) cb.certValue.getValue()).getRaw();
                if (localKeyId == null) {
                    /*
                     * Trusted certs don't have a localKeyId
                     */
                    localKeyId = friendlyName;
                } else {
                    certificates.put(localKeyId, derCert);
                }
                break;
            default:
                throw new IOException("SafeBag type not supported: " + safeBag.bagId.getString());
        }
    }
}
Also used : ASN1OctetString(com.mindbright.asn1.ASN1OctetString) CertBag(com.mindbright.security.pkcs12.CertBag) ByteArrayInputStream(java.io.ByteArrayInputStream) ASN1DER(com.mindbright.asn1.ASN1DER) EncryptedPrivateKeyInfo(com.mindbright.security.pkcs8.EncryptedPrivateKeyInfo) SafeContents(com.mindbright.security.pkcs12.SafeContents) ASN1OctetString(com.mindbright.asn1.ASN1OctetString) ASN1CharString(com.mindbright.asn1.ASN1CharString) IOException(java.io.IOException) SafeBag(com.mindbright.security.pkcs12.SafeBag)

Example 4 with CertBag

use of org.mozilla.jss.pkcs12.CertBag in project core by jcryptool.

the class AbstractImportKeyStoreEntryHandler method performImportAction.

protected void performImportAction(IImportDescriptor descriptor, Object importedObject) throws IllegalArgumentException {
    if (descriptor.getKeyStoreEntryType().equals(KeyType.SECRETKEY)) {
        if (importedObject instanceof SecretKey) {
            // $NON-NLS-1$
            LogUtil.logInfo("importing secret key");
            addSecretKey(descriptor, (SecretKey) importedObject);
        } else {
            throw new IllegalArgumentException("Parameter is not as expected an instance of SecretKey");
        }
    } else if (descriptor.getKeyStoreEntryType().equals(KeyType.KEYPAIR)) {
        if (importedObject instanceof PFX) {
            // $NON-NLS-1$
            LogUtil.logInfo("importing pfx");
            PFX pfx = (PFX) importedObject;
            try {
                char[] password = promptPassword();
                if (password == null)
                    return;
                SafeBag safeBag = pfx.getAuthSafe().getSafeContents(0).getSafeBag(0);
                PKCS8ShroudedKeyBag kBag = (PKCS8ShroudedKeyBag) safeBag.getBagValue();
                PrivateKey privKey = kBag.getPrivateKey(password);
                SafeBag certBag = pfx.getAuthSafe().getSafeContents(1, password).getSafeBag(0);
                CertBag cBag = (CertBag) certBag.getBagValue();
                PublicKey pubKey = cBag.getCertificate().getPublicKey();
                int keySize = -1;
                if (pubKey instanceof RSAPublicKey)
                    keySize = ((RSAPublicKey) pubKey).getN().bitLength();
                else if (pubKey instanceof DSAPublicKey)
                    keySize = ((DSAPublicKey) pubKey).getParameters().getP().bitLength();
                // TODO: Add keySize calculation for the remaining
                // algorithms.
                ImportDescriptor newDescriptor = new ImportDescriptor(descriptor.getContactName(), privKey.getAlgorithm(), KeyType.KEYPAIR, descriptor.getFileName(), descriptor.getPassword(), descriptor.getProvider(), keySize);
                addKeyPair(newDescriptor, privKey, pubKey);
            } catch (ASN1Exception e) {
                LogUtil.logError(KeyStorePlugin.PLUGIN_ID, "error while importing key pair", e, true);
            } catch (IOException e) {
                LogUtil.logError(KeyStorePlugin.PLUGIN_ID, "error while importing key pair", e, false);
            } catch (GeneralSecurityException e) {
                LogUtil.logError(KeyStorePlugin.PLUGIN_ID, "error while importing key pair", e, true);
            }
        } else {
            throw new IllegalArgumentException("Parameter is not an instance of PFX, as expected");
        }
    } else if (descriptor.getKeyStoreEntryType().equals(KeyType.PUBLICKEY)) {
        if (importedObject instanceof Certificate) {
            // $NON-NLS-1$
            LogUtil.logInfo("importing certificate");
            addCertificate(descriptor, (Certificate) importedObject);
        } else {
            throw new IllegalArgumentException("Parameter is not an instance of Certificate, as expected");
        }
    }
}
Also used : PKCS8ShroudedKeyBag(codec.pkcs12.PKCS8ShroudedKeyBag) PFX(codec.pkcs12.PFX) PrivateKey(java.security.PrivateKey) RSAPublicKey(de.flexiprovider.core.rsa.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) DSAPublicKey(de.flexiprovider.core.dsa.interfaces.DSAPublicKey) ASN1Exception(codec.asn1.ASN1Exception) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) SafeBag(codec.pkcs12.SafeBag) DSAPublicKey(de.flexiprovider.core.dsa.interfaces.DSAPublicKey) SecretKey(javax.crypto.SecretKey) CertBag(codec.pkcs12.CertBag) RSAPublicKey(de.flexiprovider.core.rsa.interfaces.RSAPublicKey) IImportDescriptor(org.jcryptool.crypto.keystore.descriptors.interfaces.IImportDescriptor) ImportDescriptor(org.jcryptool.crypto.keystore.descriptors.ImportDescriptor) Certificate(java.security.cert.Certificate)

Example 5 with CertBag

use of org.mozilla.jss.pkcs12.CertBag in project jss by dogtagpki.

the class PKCS12Util method getCertInfo.

public PKCS12CertInfo getCertInfo(SafeBag bag) throws Exception {
    PKCS12CertInfo certInfo = new PKCS12CertInfo();
    CertBag certBag = (CertBag) bag.getInterpretedBagContent();
    OCTET_STRING certStr = (OCTET_STRING) certBag.getInterpretedCert();
    byte[] x509cert = certStr.toByteArray();
    // generate cert ID from SHA-1 hash of cert data
    byte[] id = SafeBag.getLocalKeyIDFromCert(x509cert);
    certInfo.setID(id);
    logger.debug("   Certificate ID: " + Utils.HexEncode(id));
    X509CertImpl cert = new X509CertImpl(x509cert);
    certInfo.setCert(cert);
    X500Principal subjectDN = cert.getSubjectX500Principal();
    logger.debug("   Subject DN: " + subjectDN);
    SET bagAttrs = bag.getBagAttributes();
    for (int i = 0; bagAttrs != null && i < bagAttrs.size(); i++) {
        Attribute attr = (Attribute) bagAttrs.elementAt(i);
        OBJECT_IDENTIFIER oid = attr.getType();
        if (oid.equals(SafeBag.FRIENDLY_NAME)) {
            SET values = attr.getValues();
            ANY value = (ANY) values.elementAt(0);
            ByteArrayInputStream bis = new ByteArrayInputStream(value.getEncoded());
            BMPString friendlyName = (BMPString) (new BMPString.Template()).decode(bis);
            certInfo.setFriendlyName(friendlyName.toString());
            logger.debug("   Friendly name: " + certInfo.getFriendlyName());
        } else if (oid.equals(SafeBag.LOCAL_KEY_ID)) {
            SET values = attr.getValues();
            ANY value = (ANY) values.elementAt(0);
            ByteArrayInputStream bis = new ByteArrayInputStream(value.getEncoded());
            OCTET_STRING keyIdAsn1 = (OCTET_STRING) new OCTET_STRING.Template().decode(bis);
            byte[] keyID = keyIdAsn1.toByteArray();
            certInfo.setKeyID(keyID);
            logger.debug("   Key ID: " + Utils.HexEncode(keyID));
        } else if (oid.equals(PKCS12.CERT_TRUST_FLAGS_OID) && trustFlagsEnabled) {
            SET values = attr.getValues();
            ANY value = (ANY) values.elementAt(0);
            ByteArrayInputStream is = new ByteArrayInputStream(value.getEncoded());
            BMPString trustFlagsAsn1 = (BMPString) (new BMPString.Template()).decode(is);
            String trustFlags = trustFlagsAsn1.toString();
            certInfo.setTrustFlags(trustFlags);
            logger.debug("   Trust flags: " + trustFlags);
        } else {
            logger.warn("   " + oid + ": " + attr.getValues());
        }
    }
    if (certInfo.getFriendlyName() == null) {
        logger.debug("   Generating new friendly name");
        LdapName dn = new LdapName(subjectDN.getName());
        ArrayList<String> values = new ArrayList<>();
        // The getRdns method returns the list in reverse order
        // therefore, we must traverse in reverse order.
        List<Rdn> rdns = dn.getRdns();
        for (int i = rdns.size() - 1; i >= 0; i--) {
            Rdn rdn = rdns.get(i);
            values.add(rdn.getValue().toString());
        }
        String friendlyName = StringUtils.join(values, " - ");
        certInfo.setFriendlyName(friendlyName);
        logger.debug("   Friendly name: " + friendlyName);
    }
    return certInfo;
}
Also used : SET(org.mozilla.jss.asn1.SET) Attribute(org.mozilla.jss.pkix.primitive.Attribute) ArrayList(java.util.ArrayList) OBJECT_IDENTIFIER(org.mozilla.jss.asn1.OBJECT_IDENTIFIER) BMPString(org.mozilla.jss.asn1.BMPString) ANY(org.mozilla.jss.asn1.ANY) LdapName(javax.naming.ldap.LdapName) CertBag(org.mozilla.jss.pkcs12.CertBag) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) ByteArrayInputStream(java.io.ByteArrayInputStream) X509CertImpl(org.mozilla.jss.netscape.security.x509.X509CertImpl) X500Principal(javax.security.auth.x500.X500Principal) BMPString(org.mozilla.jss.asn1.BMPString) Rdn(javax.naming.ldap.Rdn)

Aggregations

OCTET_STRING (org.mozilla.jss.asn1.OCTET_STRING)3 SET (org.mozilla.jss.asn1.SET)3 CertBag (org.mozilla.jss.pkcs12.CertBag)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 ANY (org.mozilla.jss.asn1.ANY)2 ASN1Value (org.mozilla.jss.asn1.ASN1Value)2 BMPString (org.mozilla.jss.asn1.BMPString)2 SafeBag (org.mozilla.jss.pkcs12.SafeBag)2 ASN1Exception (codec.asn1.ASN1Exception)1 CertBag (codec.pkcs12.CertBag)1 PFX (codec.pkcs12.PFX)1 PKCS8ShroudedKeyBag (codec.pkcs12.PKCS8ShroudedKeyBag)1 SafeBag (codec.pkcs12.SafeBag)1 ASN1CharString (com.mindbright.asn1.ASN1CharString)1 ASN1DER (com.mindbright.asn1.ASN1DER)1 ASN1OctetString (com.mindbright.asn1.ASN1OctetString)1 CertBag (com.mindbright.security.pkcs12.CertBag)1 SafeBag (com.mindbright.security.pkcs12.SafeBag)1 SafeContents (com.mindbright.security.pkcs12.SafeContents)1