Search in sources :

Example 31 with NULL

use of org.mozilla.jss.asn1.NULL in project jss by dogtagpki.

the class CRLDistributionPointsExtension method main.

/**
 * Test driver.
 */
public static void main(String[] args) {
    BufferedOutputStream bos = null;
    try {
        if (args.length != 1) {
            System.out.println("Usage: CRLDistributionPointsExtentions " + "<outfile>");
            System.exit(-1);
        }
        bos = new BufferedOutputStream(new FileOutputStream(args[0]));
        // URI only
        CRLDistributionPoint cdp = new CRLDistributionPoint();
        URIName uri = new URIName("http://www.mycrl.com/go/here");
        GeneralNames generalNames = new GeneralNames();
        generalNames.addElement(uri);
        cdp.setFullName(generalNames);
        CRLDistributionPointsExtension crldpExt = new CRLDistributionPointsExtension(cdp);
        // DN only
        cdp = new CRLDistributionPoint();
        X500Name dn = new X500Name("CN=Otis Smith,E=otis@fedoraproject.org" + ",OU=Certificate Server,O=Fedora,C=US");
        generalNames = new GeneralNames();
        generalNames.addElement(dn);
        cdp.setFullName(generalNames);
        crldpExt.addPoint(cdp);
        // DN + reason
        BitArray ba = new BitArray(5, new byte[] { (byte) 0x28 });
        cdp = new CRLDistributionPoint();
        cdp.setFullName(generalNames);
        cdp.setReasons(ba);
        crldpExt.addPoint(cdp);
        // relative DN + reason + crlIssuer
        cdp = new CRLDistributionPoint();
        RDN rdn = new RDN("OU=foobar dept");
        cdp.setRelativeName(rdn);
        cdp.setReasons(ba);
        cdp.setCRLIssuer(generalNames);
        crldpExt.addPoint(cdp);
        crldpExt.setCritical(true);
        crldpExt.encode(bos);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) BitArray(org.mozilla.jss.netscape.security.util.BitArray) IOException(java.io.IOException) BufferedOutputStream(java.io.BufferedOutputStream) InvalidBERException(org.mozilla.jss.asn1.InvalidBERException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException)

Example 32 with NULL

use of org.mozilla.jss.asn1.NULL in project candlepin by candlepin.

the class JSSPKIUtility method buildStandardExtensions.

/**
 * Add boilerplate extensions required by RFC 5280.
 * @param certExtensions a CertificateExtensions object to modify
 * @param keyPair the KeyPair used to create the SubjectKeyIdentifier extension
 * @param providedExtensions A Set of provided extensions that will be added to the certificate.  In some
 * cases (hosted mode) access to the information in those extensions is required for creating the
 * subjectKeyIdentifier.
 *
 * @return a modified version of the certExtensions parameter
 * @throws IOException in case of encoding failures
 */
private CertificateExtensions buildStandardExtensions(CertificateExtensions certExtensions, String dn, KeyPair keyPair, Set<X509ExtensionWrapper> providedExtensions, X509Certificate caCert, String alternateName) throws IOException {
    /* The RFC states that KeyUsage SHOULD be marked as critical.  In previous Candlepin code we were
         * not marking it critical but this constructor will.  I do not believe there should be any
         * compatibility issues, but I am noting it just in case. */
    KeyUsageExtension keyUsage = new KeyUsageExtension();
    keyUsage.set(KeyUsageExtension.DIGITAL_SIGNATURE, true);
    keyUsage.set(KeyUsageExtension.KEY_ENCIPHERMENT, true);
    keyUsage.set(KeyUsageExtension.DATA_ENCIPHERMENT, true);
    certExtensions.add(keyUsage);
    // Not critical by default
    ExtendedKeyUsageExtension extendedKeyUsage = new ExtendedKeyUsageExtension();
    /* JSS doesn't have a constant defined for the "clientAuth" OID so we have to put it in by hand.
         * See https://tools.ietf.org/html/rfc5280#appendix-A specifically id-kp-clientAuth.  This OID
         * denotes that a certificate is meant for client authentication over TLS */
    extendedKeyUsage.addOID(new ObjectIdentifier("1.3.6.1.5.5.7.3.2"));
    certExtensions.add(extendedKeyUsage);
    // Not critical for non-CA certs.  -1 pathLen means it won't be encoded.
    BasicConstraintsExtension basicConstraints = new BasicConstraintsExtension(false, -1);
    certExtensions.add(basicConstraints);
    try {
        /* Not critical by default.  I am extremely dubious that we actually need this extension
             * but I'm keeping it because our old cert creation code added it. */
        NSCertTypeExtension netscapeCertType = new NSCertTypeExtension();
        netscapeCertType.set(NSCertTypeExtension.SSL_CLIENT, true);
        netscapeCertType.set(NSCertTypeExtension.EMAIL, true);
        certExtensions.add(netscapeCertType);
    } catch (CertificateException e) {
        throw new IOException("Could not construct certificate extensions", e);
    }
    try {
        /* The JSS SubjectKeyIdentifierExtension class expects you to give it the unencoded KeyIdentifier.
             * The SubjectKeyIdentifierExtension class, however, returns the encoded KeyIdentifier (an DER
             * octet string).  Therefore, we need to unpack the KeyIdentifier. */
        byte[] encodedSki = subjectKeyWriter.getSubjectKeyIdentifier(keyPair, providedExtensions);
        OCTET_STRING extOctets = (OCTET_STRING) ASN1Util.decode(new OCTET_STRING.Template(), encodedSki);
        // Required to be non-critical
        SubjectKeyIdentifierExtension ski = new SubjectKeyIdentifierExtension(extOctets.toByteArray());
        certExtensions.add(ski);
        // Not critical by default
        AuthorityKeyIdentifierExtension aki = buildAuthorityKeyIdentifier(caCert);
        certExtensions.add(aki);
        // Not critical by default and should *not* be critical since the subject field isn't empty
        if (alternateName != null) {
            SubjectAlternativeNameExtension altNames = new SubjectAlternativeNameExtension();
            GeneralName[] akiName = new GeneralName[2];
            akiName[0] = new GeneralName(new X500Name(dn));
            akiName[1] = new GeneralName(new X500Name("CN=" + alternateName));
            GeneralNames generalNames = new GeneralNames(akiName);
            altNames.setGeneralNames(generalNames);
            certExtensions.add(altNames);
        }
    } catch (InvalidBERException | GeneralNamesException | NoSuchAlgorithmException e) {
        throw new IOException("Could not construct certificate extensions", e);
    }
    return certExtensions;
}
Also used : ExtendedKeyUsageExtension(org.mozilla.jss.netscape.security.extensions.ExtendedKeyUsageExtension) NSCertTypeExtension(org.mozilla.jss.netscape.security.extensions.NSCertTypeExtension) SubjectAlternativeNameExtension(org.mozilla.jss.netscape.security.x509.SubjectAlternativeNameExtension) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) X500Name(org.mozilla.jss.netscape.security.x509.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SubjectKeyIdentifierExtension(org.mozilla.jss.netscape.security.x509.SubjectKeyIdentifierExtension) InvalidBERException(org.mozilla.jss.asn1.InvalidBERException) BasicConstraintsExtension(org.mozilla.jss.netscape.security.x509.BasicConstraintsExtension) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) GeneralNames(org.mozilla.jss.netscape.security.x509.GeneralNames) GeneralNamesException(org.mozilla.jss.netscape.security.x509.GeneralNamesException) AuthorityKeyIdentifierExtension(org.mozilla.jss.netscape.security.x509.AuthorityKeyIdentifierExtension) GeneralName(org.mozilla.jss.netscape.security.x509.GeneralName) KeyUsageExtension(org.mozilla.jss.netscape.security.x509.KeyUsageExtension) ExtendedKeyUsageExtension(org.mozilla.jss.netscape.security.extensions.ExtendedKeyUsageExtension) ObjectIdentifier(org.mozilla.jss.netscape.security.util.ObjectIdentifier)

Example 33 with NULL

use of org.mozilla.jss.asn1.NULL 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 34 with NULL

use of org.mozilla.jss.asn1.NULL 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 35 with NULL

use of org.mozilla.jss.asn1.NULL in project candlepin by candlepin.

the class JSSPKIUtility method createX509Certificate.

@Override
public X509Certificate createX509Certificate(String dn, Set<X509ExtensionWrapper> extensions, Set<X509ByteExtensionWrapper> byteExtensions, Date startDate, Date endDate, KeyPair clientKeyPair, BigInteger serialNumber, String alternateName) throws IOException {
    // Ensure JSS is properly initialized before attempting any operations with it
    JSSProviderLoader.initialize();
    X509CertInfo certInfo = new X509CertInfo();
    try {
        X509Certificate caCert = reader.getCACert();
        byte[] publicKeyEncoded = clientKeyPair.getPublic().getEncoded();
        certInfo.set(X509CertInfo.ISSUER, new CertificateIssuerName(new X500Name(caCert.getSubjectX500Principal().getEncoded())));
        certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(serialNumber));
        certInfo.set(X509CertInfo.VALIDITY, new CertificateValidity(startDate, endDate));
        certInfo.set(X509CertInfo.SUBJECT, new CertificateSubjectName(new X500Name(dn)));
        certInfo.set(X509CertInfo.KEY, new CertificateX509Key(X509Key.parse(new DerValue(publicKeyEncoded))));
        certInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(AlgorithmId.get(SIGNING_ALG_ID)));
        certInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
        CertificateExtensions certExtensions = buildStandardExtensions(new CertificateExtensions(), dn, clientKeyPair, extensions, caCert, alternateName);
        certInfo.set(X509CertInfo.EXTENSIONS, certExtensions);
        if (extensions != null) {
            for (X509ExtensionWrapper wrapper : extensions) {
                // Avoid null values. Set them to blank if they are null
                String value = wrapper.getValue() == null ? "" : wrapper.getValue();
                UTF8String der = new UTF8String(value);
                certExtensions.add(buildCustomExtension(wrapper.getOid(), wrapper.isCritical(), der));
            }
        }
        if (byteExtensions != null) {
            for (X509ByteExtensionWrapper wrapper : byteExtensions) {
                // Avoid null values. Set them to blank if they are null
                byte[] value = wrapper.getValue() == null ? new byte[0] : wrapper.getValue();
                OCTET_STRING der = new OCTET_STRING(value);
                certExtensions.add(buildCustomExtension(wrapper.getOid(), wrapper.isCritical(), der));
            }
        }
        X509CertImpl certImpl = new X509CertImpl(certInfo);
        certImpl.sign(reader.getCaKey(), SIGNING_ALG_ID);
        // valid, it just won't have any extensions present in the object.
        return new X509CertImpl(certImpl.getEncoded());
    } catch (GeneralSecurityException e) {
        throw new RuntimeException("Could not create X.509 certificate", e);
    }
}
Also used : CertificateSubjectName(org.mozilla.jss.netscape.security.x509.CertificateSubjectName) UTF8String(org.mozilla.jss.asn1.UTF8String) X509CertInfo(org.mozilla.jss.netscape.security.x509.X509CertInfo) CertificateIssuerName(org.mozilla.jss.netscape.security.x509.CertificateIssuerName) GeneralSecurityException(java.security.GeneralSecurityException) CertificateVersion(org.mozilla.jss.netscape.security.x509.CertificateVersion) CertificateValidity(org.mozilla.jss.netscape.security.x509.CertificateValidity) CertificateExtensions(org.mozilla.jss.netscape.security.x509.CertificateExtensions) X500Name(org.mozilla.jss.netscape.security.x509.X500Name) UTF8String(org.mozilla.jss.asn1.UTF8String) CertificateX509Key(org.mozilla.jss.netscape.security.x509.CertificateX509Key) X509Certificate(java.security.cert.X509Certificate) CertificateSerialNumber(org.mozilla.jss.netscape.security.x509.CertificateSerialNumber) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) TokenRuntimeException(org.mozilla.jss.crypto.TokenRuntimeException) DerValue(org.mozilla.jss.netscape.security.util.DerValue) X509CertImpl(org.mozilla.jss.netscape.security.x509.X509CertImpl) X509ByteExtensionWrapper(org.candlepin.pki.X509ByteExtensionWrapper) X509ExtensionWrapper(org.candlepin.pki.X509ExtensionWrapper) CertificateAlgorithmId(org.mozilla.jss.netscape.security.x509.CertificateAlgorithmId)

Aggregations

SEQUENCE (org.mozilla.jss.asn1.SEQUENCE)33 OCTET_STRING (org.mozilla.jss.asn1.OCTET_STRING)19 InvalidBERException (org.mozilla.jss.asn1.InvalidBERException)17 ANY (org.mozilla.jss.asn1.ANY)14 CryptoToken (org.mozilla.jss.crypto.CryptoToken)14 AlgorithmIdentifier (org.mozilla.jss.pkix.primitive.AlgorithmIdentifier)11 IOException (java.io.IOException)10 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)10 ASN1Value (org.mozilla.jss.asn1.ASN1Value)10 BMPString (org.mozilla.jss.asn1.BMPString)10 CryptoManager (org.mozilla.jss.CryptoManager)9 SET (org.mozilla.jss.asn1.SET)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)8 OBJECT_IDENTIFIER (org.mozilla.jss.asn1.OBJECT_IDENTIFIER)8 EncryptionAlgorithm (org.mozilla.jss.crypto.EncryptionAlgorithm)8 FileOutputStream (java.io.FileOutputStream)7 Cipher (org.mozilla.jss.crypto.Cipher)7 CertificateException (java.security.cert.CertificateException)6 BadPaddingException (javax.crypto.BadPaddingException)6