Search in sources :

Example 1 with NULL

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

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

the class Decryptor method decrypt.

/**
 * Decrypts the given ciphertext. It must have been created previously
 * with the SecretDecoderRing, either the JSS version or the NSS version.
 * The key used for decryption must exist on the token that was passed
 * into the constructor. The token will be searched for a key whose keyID
 * matches the keyID in the encoded SecretDecoderRing result.
 *
 * @param ciphertext A DER-encoded Encoding object, created from a previous
 *  call to Encryptor.encrypt(), or with the NSS SecretDecoderRing.
 * @return The decrypted plaintext.
 * @throws InvalidKeyException If no key can be found with the matching
 *  keyID.
 */
public byte[] decrypt(byte[] ciphertext) throws NotInitializedException, GeneralSecurityException, TokenException {
    CryptoManager cm = CryptoManager.getInstance();
    CryptoToken savedToken = cm.getThreadToken();
    try {
        cm.setThreadToken(token);
        // 
        // decode ASN1
        // 
        Encoding encoding = (Encoding) ASN1Util.decode(Encoding.getTemplate(), ciphertext);
        // 
        // lookup the algorithm
        // 
        EncryptionAlgorithm alg = EncryptionAlgorithm.fromOID(encoding.getEncryptionOID());
        // 
        // Lookup the key
        // 
        SecretKey key = keyManager.lookupKey(alg, encoding.getKeyID());
        if (key == null) {
            throw new InvalidKeyException("No matching key found");
        }
        // 
        // do the decryption
        // 
        IvParameterSpec ivSpec = new IvParameterSpec(encoding.getIv());
        Cipher cipher = Cipher.getInstance(alg.toString(), Encryptor.PROVIDER);
        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
        byte[] paddedPtext = cipher.doFinal(encoding.getCiphertext());
        return org.mozilla.jss.crypto.Cipher.unPad(paddedPtext, alg.getBlockSize());
    } catch (InvalidBERException ibe) {
        throw new GeneralSecurityException(ibe.toString());
    } catch (IllegalStateException ise) {
        throw new GeneralSecurityException(ise.toString());
    } finally {
        cm.setThreadToken(savedToken);
    }
}
Also used : InvalidBERException(org.mozilla.jss.asn1.InvalidBERException) SecretKey(javax.crypto.SecretKey) CryptoToken(org.mozilla.jss.crypto.CryptoToken) GeneralSecurityException(java.security.GeneralSecurityException) EncryptionAlgorithm(org.mozilla.jss.crypto.EncryptionAlgorithm) CryptoManager(org.mozilla.jss.CryptoManager) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) InvalidKeyException(java.security.InvalidKeyException)

Example 3 with NULL

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

the class JSSUtil method decode.

public static String decode(byte tag, byte[] bytes) throws Exception {
    ASN1Template template;
    switch(tag) {
        case DerValue.tag_BMPString:
            template = new BMPString.Template();
            break;
        case DerValue.tag_IA5String:
            template = new IA5String.Template();
            break;
        case DerValue.tag_PrintableString:
            template = new PrintableString.Template();
            break;
        case DerValue.tag_T61String:
            template = new TeletexString.Template();
            break;
        case DerValue.tag_UniversalString:
            template = new UniversalString.Template();
            break;
        case DerValue.tag_UTF8String:
            template = new UTF8String.Template();
            break;
        default:
            throw new Exception("Unsupported tag: " + tag);
    }
    ASN1Value asnValue = ASN1Util.decode(new Tag(Tag.UNIVERSAL, tag), template, bytes);
    if (asnValue == null) {
        throw new Exception("Cannot decode the given bytes.");
    }
    return asnValue.toString();
}
Also used : ASN1Template(org.mozilla.jss.asn1.ASN1Template) UTF8String(org.mozilla.jss.asn1.UTF8String) PrintableString(org.mozilla.jss.asn1.PrintableString) TeletexString(org.mozilla.jss.asn1.TeletexString) ASN1Value(org.mozilla.jss.asn1.ASN1Value) IA5String(org.mozilla.jss.asn1.IA5String) Tag(org.mozilla.jss.asn1.Tag) UniversalString(org.mozilla.jss.asn1.UniversalString) BMPString(org.mozilla.jss.asn1.BMPString)

Example 4 with NULL

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

the class SSLClientAuth method makeCert.

/**
 * Method that generates a certificate for given credential
 *
 * @param issuerName
 * @param subjectName
 * @param serialNumber
 * @param privKey
 * @param pubKey
 * @param rand
 * @param extensions
 * @throws java.lang.Exception
 * @return Certificate
 */
public static Certificate makeCert(String issuerName, String subjectName, int serialNumber, PrivateKey privKey, PublicKey pubKey, int rand, SEQUENCE extensions) throws Exception {
    AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(sigAlg.toOID());
    Name issuer = new Name();
    issuer.addCountryName("US");
    issuer.addOrganizationName("Mozilla");
    issuer.addOrganizationalUnitName("JSS Testing" + rand);
    issuer.addCommonName(issuerName);
    Name subject = new Name();
    subject.addCountryName("US");
    subject.addOrganizationName("Mozilla");
    subject.addOrganizationalUnitName("JSS Testing" + rand);
    subject.addCommonName(subjectName);
    Calendar cal = Calendar.getInstance();
    Date notBefore = cal.getTime();
    cal.add(Calendar.YEAR, 1);
    Date notAfter = cal.getTime();
    SubjectPublicKeyInfo.Template spkiTemp = new SubjectPublicKeyInfo.Template();
    SubjectPublicKeyInfo spki = (SubjectPublicKeyInfo) ASN1Util.decode(spkiTemp, pubKey.getEncoded());
    CertificateInfo info = new CertificateInfo(CertificateInfo.v3, new INTEGER(serialNumber), sigAlgID, issuer, notBefore, notAfter, subject, spki);
    if (extensions != null) {
        info.setExtensions(extensions);
    }
    return new Certificate(info, privKey, sigAlg);
}
Also used : Calendar(java.util.Calendar) CertificateInfo(org.mozilla.jss.pkix.cert.CertificateInfo) SubjectPublicKeyInfo(org.mozilla.jss.pkix.primitive.SubjectPublicKeyInfo) Date(java.util.Date) AlgorithmIdentifier(org.mozilla.jss.pkix.primitive.AlgorithmIdentifier) Name(org.mozilla.jss.pkix.primitive.Name) INTEGER(org.mozilla.jss.asn1.INTEGER) InternalCertificate(org.mozilla.jss.crypto.InternalCertificate) Certificate(org.mozilla.jss.pkix.cert.Certificate) X509Certificate(org.mozilla.jss.crypto.X509Certificate)

Example 5 with NULL

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

the class GenerateTestCert method doIt.

/**
 * Based on the input parameters, generate a cert
 * pair.
 */
private void doIt(String[] args) throws Exception {
    String caCertNick = CACERT_NICKNAME;
    String serverCertNick = SERVERCERT_NICKNAME;
    String clientCertNick = CLIENTCERT_NICKNAME;
    if (args.length < 3) {
        usage();
    }
    try {
        CryptoManager cm = CryptoManager.getInstance();
        CryptoToken tok = cm.getInternalKeyStorageToken();
        PasswordCallback cb = new FilePasswordCallback(args[1]);
        tok.login(cb);
        int serialNum = Integer.parseInt(args[2]);
        X509Certificate[] permCerts = cm.getPermCerts();
        int originalPermCerts = permCerts.length;
        System.out.println("Number of certificates stored in the " + " database: " + originalPermCerts);
        String hostname = "localhost";
        if (args.length > 4) {
            hostname = args[3];
        }
        String alg = "SHA-256/RSA";
        if (args.length > 5) {
            alg = args[4];
        }
        setSigAlg(alg);
        X509Certificate[] certs;
        if (args.length > 6) {
            caCertNick = args[5];
        }
        /* ensure certificate does not already exists */
        certs = cm.findCertsByNickname(caCertNick);
        if (certs.length > 0) {
            System.out.println(caCertNick + " already exists!");
            System.exit(1);
        }
        if (args.length > 7) {
            serverCertNick = args[6];
        }
        certs = cm.findCertsByNickname(serverCertNick);
        if (certs.length > 0) {
            System.out.println(serverCertNick + " already exists!");
            System.exit(1);
        }
        if (args.length == 8) {
            clientCertNick = args[7];
        }
        certs = cm.findCertsByNickname(clientCertNick);
        if (certs.length > 0) {
            System.out.println(clientCertNick + " already exists!");
            System.exit(1);
        }
        // generate CA cert
        java.security.KeyPairGenerator kpg = java.security.KeyPairGenerator.getInstance(keyType, "Mozilla-JSS");
        kpg.initialize(keyLength);
        KeyPair caPair = kpg.genKeyPair();
        SEQUENCE extensions = new SEQUENCE();
        extensions.addElement(makeBasicConstraintsExtension());
        Certificate caCert = makeCert("CACert", "CACert", serialNum, caPair.getPrivate(), caPair.getPublic(), serialNum, extensions);
        X509Certificate nssCaCert = cm.importUserCACertPackage(ASN1Util.encode(caCert), caCertNick);
        InternalCertificate intern = (InternalCertificate) nssCaCert;
        intern.setSSLTrust(PK11Cert.TRUSTED_CA | PK11Cert.TRUSTED_CLIENT_CA | PK11Cert.VALID_CA);
        // generate server cert
        kpg.initialize(keyLength);
        KeyPair serverPair = kpg.genKeyPair();
        Certificate serverCert = makeCert("CACert", hostname, serialNum + 1, caPair.getPrivate(), serverPair.getPublic(), serialNum, null);
        nssServerCert = cm.importCertPackage(ASN1Util.encode(serverCert), serverCertNick);
        // generate client auth cert
        kpg.initialize(keyLength);
        KeyPair clientPair = kpg.genKeyPair();
        Certificate clientCert = makeCert("CACert", "ClientCert", serialNum + 2, caPair.getPrivate(), clientPair.getPublic(), serialNum, null);
        nssClientCert = cm.importCertPackage(ASN1Util.encode(clientCert), clientCertNick);
        System.out.println("\nThis program created certificates with \n" + "following cert nicknames:" + "\n\t" + caCertNick + "\n\t" + serverCertNick + "\n\t" + clientCertNick);
        permCerts = cm.getPermCerts();
        if ((originalPermCerts + 3) != permCerts.length) {
            System.out.println("Error there should be three more " + " certificates stored in the database");
            System.exit(1);
        } else {
            System.out.println("Number of certificates stored in the " + " database: " + permCerts.length);
        }
        /* ensure certificates exists */
        certs = cm.findCertsByNickname(caCertNick);
        if (certs.length == 0) {
            System.out.println(caCertNick + " should exist!");
            System.exit(1);
        }
        certs = cm.findCertsByNickname(serverCertNick);
        if (certs.length == 0) {
            System.out.println(serverCertNick + " should exist!");
            System.exit(1);
        }
        certs = cm.findCertsByNickname(clientCertNick);
        if (certs.length == 0) {
            System.out.println(clientCertNick + " should exist!");
            System.exit(1);
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}
Also used : KeyPair(java.security.KeyPair) CryptoToken(org.mozilla.jss.crypto.CryptoToken) CryptoManager(org.mozilla.jss.CryptoManager) X509Certificate(org.mozilla.jss.crypto.X509Certificate) InternalCertificate(org.mozilla.jss.crypto.InternalCertificate) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) PasswordCallback(org.mozilla.jss.util.PasswordCallback) Certificate(org.mozilla.jss.pkix.cert.Certificate) InternalCertificate(org.mozilla.jss.crypto.InternalCertificate) X509Certificate(org.mozilla.jss.crypto.X509Certificate)

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