Search in sources :

Example 6 with PFX

use of com.mindbright.security.pkcs12.PFX in project OpenAM by OpenRock.

the class SecureLogHelperJSSImpl method readFromSecretStore.

/**
     * Returns matched secret data from from the secret Storage. 
     * At a time there are only 3 things in logger's secure store file 
     *    - initialkey, currentkey and current signature
     * In the verifier secure store file there is just the initial key of the
     * logger and the currentKey
     * @param filename file for secret storage
     * @param dataType The kind of data to be read, whether it is a
     *                 signature or a key
     * @param password password for the file
     * @return secure data that is matched with dataType
     * @throws Exception if it fails to read secret data from secret store
     */
byte[] readFromSecretStore(String filename, String dataType, AMPassword password) throws Exception {
    // open input file for reading
    FileInputStream infile = null;
    infile = new FileInputStream(filename);
    // Decode the P12 file
    PFX.Template pfxt = new PFX.Template();
    PFX pfx = (PFX) pfxt.decode(new BufferedInputStream(infile, 2048));
    // Verify the MAC on the PFX.  This is important to be sure
    // it hasn't been tampered with.
    StringBuffer reason = new StringBuffer();
    MessageDigest md = MessageDigest.getInstance("SHA");
    Password jssPasswd = new Password(new String(md.digest(password.getByteCopy()), "UTF-8").toCharArray());
    md.reset();
    if (!pfx.verifyAuthSafes(jssPasswd, reason)) {
        throw new Exception("AuthSafes failed to verify because: " + reason.toString());
    }
    AuthenticatedSafes authSafes = pfx.getAuthSafes();
    SEQUENCE safeContentsSequence = authSafes.getSequence();
    byte[] cryptoData = null;
    // Loop over contents of the authenticated safes
    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(jssPasswd, i);
        SafeBag safeBag = null;
        ASN1Value val = null;
        // Go through all the bags in this SafeContents
        for (int j = 0; j < safeContents.size(); j++) {
            safeBag = (SafeBag) safeContents.elementAt(j);
            // look for bag attributes and then choose the key
            SET attribs = safeBag.getBagAttributes();
            if (attribs == null) {
                Debug.error("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());
                        if (dataType.equals(bs.toString())) {
                            // look at the contents of the bag
                            val = safeBag.getInterpretedBagContent();
                            break;
                        }
                    }
                }
            }
        }
        if (val instanceof ANY)
            cryptoData = ((ANY) val).getContents();
    }
    // Close the file
    infile.close();
    return cryptoData;
}
Also used : PFX(org.mozilla.jss.pkcs12.PFX) SET(org.mozilla.jss.asn1.SET) Attribute(org.mozilla.jss.pkix.primitive.Attribute) BMPString(org.mozilla.jss.asn1.BMPString) SafeBag(org.mozilla.jss.pkcs12.SafeBag) ANY(org.mozilla.jss.asn1.ANY) FileInputStream(java.io.FileInputStream) AuthenticatedSafes(org.mozilla.jss.pkcs12.AuthenticatedSafes) ASN1Value(org.mozilla.jss.asn1.ASN1Value) BufferedInputStream(java.io.BufferedInputStream) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) MessageDigest(java.security.MessageDigest) BMPString(org.mozilla.jss.asn1.BMPString) AMPassword(com.sun.identity.security.keystore.AMPassword) Password(org.mozilla.jss.util.Password)

Example 7 with PFX

use of com.mindbright.security.pkcs12.PFX in project OpenAM by OpenRock.

the class SecureLogHelperJSSImpl method writeToSecretStore.

/**
     * Writes to the secret Storage. If the data to be written is a key, then
     * writes the older signature also. If it is a signature then writes the
     * older key also
     * @param cryptoMaterial The data to be written to the secret storage
     * @param filename The file for secret storage
     * @param password The password for the file
     * @param dataType The kind of cryptoMaterial, whether it is a signature
     * or a key
     * @throws Exception if it fails to write secret data from secret store
     */
void writeToSecretStore(byte[] cryptoMaterial, String filename, AMPassword password, String dataType) throws Exception {
    byte[] oldDataFromSecretStorage = null;
    String oldDataType = null;
    MessageDigest md = MessageDigest.getInstance("SHA");
    Password jssPasswd = new Password(new String(md.digest(password.getByteCopy()), "UTF-8").toCharArray());
    md.reset();
    // Do this only when the logger's file is being used
    if (filename.equals(logFileName) && loggerInitialized) {
        // current signature in the PKCS12 file
        if (dataType.equals(currentSignature)) {
            oldDataFromSecretStorage = readFromSecretStore(logFileName, currentKey, password);
            oldDataType = currentKey;
        } else if (dataType.equals(currentKey)) {
            // need to read the currentSignature 
            // for the same reason as above
            oldDataFromSecretStorage = readFromSecretStore(logFileName, currentSignature, password);
            oldDataType = currentSignature;
        }
    }
    // Start building the new contents by adding the older content first
    AuthenticatedSafes newAuthSafes = new AuthenticatedSafes();
    if (oldDataFromSecretStorage != null) {
        SEQUENCE oldSafeContents = AddToSecretStore(oldDataFromSecretStorage, oldDataType);
        // Add the old contents to the existing safe
        newAuthSafes.addEncryptedSafeContents(PBEAlgorithm.PBE_SHA1_DES3_CBC, jssPasswd, null, AuthenticatedSafes.DEFAULT_ITERATIONS, oldSafeContents);
    }
    // not being added for the first time
    if ((filename.equals(logFileName)) && !dataType.equals(initialKey) && loggerInitialized) {
        byte[] key = readFromSecretStore(filename, initialKey, password);
        if (key != null) {
            SEQUENCE initialKeySafeContents = AddToSecretStore(key, initialKey);
            newAuthSafes.addEncryptedSafeContents(PBEAlgorithm.PBE_SHA1_DES3_CBC, jssPasswd, null, AuthenticatedSafes.DEFAULT_ITERATIONS, initialKeySafeContents);
        }
    }
    if ((filename.equals(verifierFileName)) && !dataType.equals(initialKey) && verifierInitialized) {
        byte[] key = readFromSecretStore(filename, initialKey, password);
        if (key != null) {
            SEQUENCE initialKeySafeContents = AddToSecretStore(key, initialKey);
            newAuthSafes.addEncryptedSafeContents(PBEAlgorithm.PBE_SHA1_DES3_CBC, jssPasswd, null, AuthenticatedSafes.DEFAULT_ITERATIONS, initialKeySafeContents);
        }
    }
    // Add the new contents
    SEQUENCE encSafeContents = AddToSecretStore(cryptoMaterial, dataType);
    // Add the new contents to the existing safe
    newAuthSafes.addEncryptedSafeContents(PBEAlgorithm.PBE_SHA1_DES3_CBC, jssPasswd, null, AuthenticatedSafes.DEFAULT_ITERATIONS, encSafeContents);
    PFX newpfx = new PFX(newAuthSafes);
    newpfx.computeMacData(jssPasswd, null, 5);
    // write the new PFX out to the logger
    FileOutputStream fos = new FileOutputStream(filename);
    newpfx.encode(fos);
    fos.close();
}
Also used : PFX(org.mozilla.jss.pkcs12.PFX) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) FileOutputStream(java.io.FileOutputStream) BMPString(org.mozilla.jss.asn1.BMPString) MessageDigest(java.security.MessageDigest) AMPassword(com.sun.identity.security.keystore.AMPassword) Password(org.mozilla.jss.util.Password) AuthenticatedSafes(org.mozilla.jss.pkcs12.AuthenticatedSafes)

Example 8 with PFX

use of com.mindbright.security.pkcs12.PFX in project core by jcryptool.

the class ImportKeyHandler method execute.

public Object execute(ExecutionEvent event) {
    shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
    Wizard wizard = new ImportWizard();
    dialog = new WizardDialog(shell, wizard);
    dialog.setMinimumPageSize(300, 350);
    int result = dialog.open();
    if (result == Window.OK) {
        if (wizard instanceof IImportWizard) {
            IImportDescriptor desc = ((IImportWizard) wizard).getImportDescriptor();
            IPath path = new Path(desc.getFileName());
            if (desc.getKeyStoreEntryType().equals(KeyType.SECRETKEY)) {
                SecretKey key = ImportManager.getInstance().importSecretKey(path);
                performImportAction(new ImportDescriptor(desc.getContactName(), key.getAlgorithm(), KeyType.SECRETKEY, desc.getFileName(), desc.getPassword(), // $NON-NLS-1$
                "FlexiCore", -1), key);
            } else if (desc.getKeyStoreEntryType().equals(KeyType.KEYPAIR)) {
                PFX pfx = ImportManager.getInstance().importPFX(path);
                performImportAction(desc, pfx);
            } else if (desc.getKeyStoreEntryType().equals(KeyType.PUBLICKEY)) {
                Certificate cert = ImportManager.getInstance().importCertificate(path);
                performImportAction(desc, cert);
            }
        }
    }
    return (null);
}
Also used : IPath(org.eclipse.core.runtime.IPath) Path(org.eclipse.core.runtime.Path) SecretKey(javax.crypto.SecretKey) PFX(codec.pkcs12.PFX) ImportWizard(org.jcryptool.crypto.flexiprovider.keystore.wizards.ImportWizard) IImportWizard(org.jcryptool.crypto.keystore.descriptors.interfaces.IImportWizard) IPath(org.eclipse.core.runtime.IPath) IImportWizard(org.jcryptool.crypto.keystore.descriptors.interfaces.IImportWizard) IImportDescriptor(org.jcryptool.crypto.keystore.descriptors.interfaces.IImportDescriptor) ImportDescriptor(org.jcryptool.crypto.keystore.descriptors.ImportDescriptor) Wizard(org.eclipse.jface.wizard.Wizard) ImportWizard(org.jcryptool.crypto.flexiprovider.keystore.wizards.ImportWizard) IImportWizard(org.jcryptool.crypto.keystore.descriptors.interfaces.IImportWizard) WizardDialog(org.eclipse.jface.wizard.WizardDialog) IImportDescriptor(org.jcryptool.crypto.keystore.descriptors.interfaces.IImportDescriptor) Certificate(java.security.cert.Certificate)

Example 9 with PFX

use of com.mindbright.security.pkcs12.PFX in project jss by dogtagpki.

the class PKCS12Util method loadFromByteArray.

public PKCS12 loadFromByteArray(byte[] b, Password password) throws Exception {
    ByteArrayInputStream bis = new ByteArrayInputStream(b);
    PFX pfx = (PFX) (new PFX.Template()).decode(bis);
    PKCS12 pkcs12 = new PKCS12();
    StringBuffer reason = new StringBuffer();
    boolean valid = pfx.verifyAuthSafes(password, reason);
    if (!valid) {
        throw new Exception("Unable to validate PKCS #12 file: " + reason);
    }
    getKeyInfos(pkcs12, pfx, password);
    getCertInfos(pkcs12, pfx, password);
    return pkcs12;
}
Also used : PFX(org.mozilla.jss.pkcs12.PFX) ByteArrayInputStream(java.io.ByteArrayInputStream) NoSuchItemOnTokenException(org.mozilla.jss.crypto.NoSuchItemOnTokenException) ObjectNotFoundException(org.mozilla.jss.crypto.ObjectNotFoundException) CertificateException(java.security.cert.CertificateException) InvalidNameException(javax.naming.InvalidNameException)

Example 10 with PFX

use of com.mindbright.security.pkcs12.PFX in project jss by dogtagpki.

the class PKCS12Util method generatePFX.

public PFX generatePFX(PKCS12 pkcs12, Password password) throws Exception {
    logger.info("Generating PKCS #12 data");
    AuthenticatedSafes authSafes = new AuthenticatedSafes();
    Collection<PKCS12KeyInfo> keyInfos = pkcs12.getKeyInfos();
    Collection<PKCS12CertInfo> certInfos = pkcs12.getCertInfos();
    if (!keyInfos.isEmpty()) {
        SEQUENCE keySafeContents = new SEQUENCE();
        for (PKCS12KeyInfo keyInfo : keyInfos) {
            addKeyBag(keyInfo, password, keySafeContents);
        }
        authSafes.addSafeContents(keySafeContents);
    }
    if (!certInfos.isEmpty()) {
        SEQUENCE certSafeContents = new SEQUENCE();
        for (PKCS12CertInfo certInfo : certInfos) {
            addCertBag(certInfo, certSafeContents);
        }
        if (certEncryption == null) {
            authSafes.addSafeContents(certSafeContents);
        } else if (certEncryption == PBEAlgorithm.PBE_SHA1_RC2_40_CBC) {
            byte[] salt = new byte[16];
            random.nextBytes(salt);
            authSafes.addEncryptedSafeContents(certEncryption, password, salt, // iterations
            100000, certSafeContents);
        } else {
            throw new Exception("Unsupported certificate encryption: " + certEncryption);
        }
    }
    PFX pfx = new PFX(authSafes);
    // Use the same salt size and number of iterations as in pk12util.
    byte[] salt = new byte[16];
    random.nextBytes(salt);
    pfx.computeMacData(password, salt, 100000);
    return pfx;
}
Also used : PFX(org.mozilla.jss.pkcs12.PFX) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) NoSuchItemOnTokenException(org.mozilla.jss.crypto.NoSuchItemOnTokenException) ObjectNotFoundException(org.mozilla.jss.crypto.ObjectNotFoundException) CertificateException(java.security.cert.CertificateException) InvalidNameException(javax.naming.InvalidNameException) AuthenticatedSafes(org.mozilla.jss.pkcs12.AuthenticatedSafes)

Aggregations

PFX (org.mozilla.jss.pkcs12.PFX)6 PFX (codec.pkcs12.PFX)4 IOException (java.io.IOException)4 SEQUENCE (org.mozilla.jss.asn1.SEQUENCE)4 ASN1Exception (codec.asn1.ASN1Exception)3 BufferedInputStream (java.io.BufferedInputStream)3 FileOutputStream (java.io.FileOutputStream)3 BMPString (org.mozilla.jss.asn1.BMPString)3 AuthenticatedSafes (org.mozilla.jss.pkcs12.AuthenticatedSafes)3 AMPassword (com.sun.identity.security.keystore.AMPassword)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 FileInputStream (java.io.FileInputStream)2 GeneralSecurityException (java.security.GeneralSecurityException)2 MessageDigest (java.security.MessageDigest)2 Certificate (java.security.cert.Certificate)2 CertificateException (java.security.cert.CertificateException)2 SecretKey (javax.crypto.SecretKey)2 InvalidNameException (javax.naming.InvalidNameException)2 IFileStore (org.eclipse.core.filesystem.IFileStore)2