Search in sources :

Example 1 with AlgorithmIdentifier

use of org.mozilla.jss.pkix.primitive.AlgorithmIdentifier 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 2 with AlgorithmIdentifier

use of org.mozilla.jss.pkix.primitive.AlgorithmIdentifier in project jss by dogtagpki.

the class GenerateTestCert 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
 */
private 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) Certificate(org.mozilla.jss.pkix.cert.Certificate) InternalCertificate(org.mozilla.jss.crypto.InternalCertificate) X509Certificate(org.mozilla.jss.crypto.X509Certificate)

Example 3 with AlgorithmIdentifier

use of org.mozilla.jss.pkix.primitive.AlgorithmIdentifier in project jss by dogtagpki.

the class CertReqMsg method verify.

public void verify(CryptoToken token) throws SignatureException, InvalidKeyFormatException, NoSuchAlgorithmException, org.mozilla.jss.NotInitializedException, TokenException, java.security.InvalidKeyException, IOException {
    ProofOfPossession.Type type = pop.getType();
    if (type == ProofOfPossession.SIGNATURE) {
        POPOSigningKey sigkey = pop.getSignature();
        AlgorithmIdentifier alg = sigkey.getAlgorithmIdentifier();
        BIT_STRING sig_from = sigkey.getSignature();
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        certReq.encode(bo);
        byte[] toBeVerified = bo.toByteArray();
        PublicKey pubkey = null;
        CertTemplate ct = certReq.getCertTemplate();
        if (ct.hasPublicKey()) {
            SubjectPublicKeyInfo spi = ct.getPublicKey();
            pubkey = spi.toPublicKey();
        }
        SignatureAlgorithm sigAlg = SignatureAlgorithm.fromOID(alg.getOID());
        Signature sig = token.getSignatureContext(sigAlg);
        sig.initVerify(pubkey);
        sig.update(toBeVerified);
        if (sig.verify(sig_from.getBits())) {
            // success
            return;
        } else {
            throw new SignatureException("Signed request information does not " + "match signature in POP");
        }
    } else if (type == ProofOfPossession.KEY_ENCIPHERMENT) {
        POPOPrivKey keyEnc = pop.getKeyEncipherment();
        POPOPrivKey.Type ptype = keyEnc.getType();
        if (ptype == POPOPrivKey.THIS_MESSAGE) {
        // BIT_STRING thisMessage = keyEnc.getThisMessage();
        // This should be the same as from the archive control
        // It's verified by DRM.
        } else if (ptype == POPOPrivKey.SUBSEQUENT_MESSAGE) {
            new ChallengeResponseException("requested");
        }
    }
}
Also used : PublicKey(java.security.PublicKey) SignatureAlgorithm(org.mozilla.jss.crypto.SignatureAlgorithm) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SignatureException(java.security.SignatureException) SubjectPublicKeyInfo(org.mozilla.jss.pkix.primitive.SubjectPublicKeyInfo) BIT_STRING(org.mozilla.jss.asn1.BIT_STRING) AlgorithmIdentifier(org.mozilla.jss.pkix.primitive.AlgorithmIdentifier) Signature(org.mozilla.jss.crypto.Signature)

Example 4 with AlgorithmIdentifier

use of org.mozilla.jss.pkix.primitive.AlgorithmIdentifier in project jss by dogtagpki.

the class KeyFactorySpi1_2 method engineGeneratePublic.

@Override
protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecException {
    if (keySpec instanceof RSAPublicKeySpec) {
        RSAPublicKeySpec spec = (RSAPublicKeySpec) keySpec;
        // Generate a DER RSA public key
        SEQUENCE seq = new SEQUENCE();
        seq.addElement(new INTEGER(spec.getModulus()));
        seq.addElement(new INTEGER(spec.getPublicExponent()));
        return PK11PubKey.fromRaw(PrivateKey.RSA, ASN1Util.encode(seq));
    } else if (keySpec instanceof DSAPublicKeySpec) {
        // We need to import both the public value and the PQG parameters.
        // The only way to get all that information in DER is to send
        // a full SubjectPublicKeyInfo. So we encode all the information
        // into an SPKI.
        DSAPublicKeySpec spec = (DSAPublicKeySpec) keySpec;
        SEQUENCE pqg = new SEQUENCE();
        pqg.addElement(new INTEGER(spec.getP()));
        pqg.addElement(new INTEGER(spec.getQ()));
        pqg.addElement(new INTEGER(spec.getG()));
        OBJECT_IDENTIFIER oid = null;
        try {
            oid = SignatureAlgorithm.DSASignature.toOID();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("No such algorithm: " + e.getMessage(), e);
        }
        AlgorithmIdentifier algID = new AlgorithmIdentifier(oid, pqg);
        INTEGER publicValue = new INTEGER(spec.getY());
        byte[] encodedPublicValue = ASN1Util.encode(publicValue);
        SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(algID, new BIT_STRING(encodedPublicValue, 0));
        return PK11PubKey.fromSPKI(ASN1Util.encode(spki));
    // 
    // requires JAVA 1.5
    // 
    // } else if( keySpec instanceof ECPublicKeySpec ) {
    // // We need to import both the public value and the curve.
    // // The only way to get all that information in DER is to send
    // // a full SubjectPublicKeyInfo. So we encode all the information
    // // into an SPKI.
    // 
    // ECPublicKeySpec spec = (ECPublicKeySpec) keySpec;
    // AlgorithmParameters algParams = getInstance("ECParameters");
    // 
    // algParameters.init(spec.getECParameters());
    // OBJECT_IDENTIFIER oid = null;
    // try {
    // oid = SignatureAlgorithm.ECSignature.toOID();
    // } catch(NoSuchAlgorithmException ex ) {
    // Assert.notReached("no such algorithm as DSA?");
    // }
    // AlgorithmIdentifier algID =
    // new AlgorithmIdentifier(oid, ecParams.getParams() );
    // INTEGER publicValueX = new INTEGER(spec.getW().getAffineX());
    // INTEGER publicValueY = new INTEGER(spec.getW().getAffineY());
    // byte[] encodedPublicValue;
    // encodedPublicValue[0] = EC_UNCOMPRESSED_POINT;
    // encodedPublicValue += spec.getW().getAffineX().toByteArray();
    // encodedPublicValue += spec.getW().getAffineY().toByteArray();
    // 
    // byte[] encodedPublicValue = ASN1Util.encode(publicValue);
    // SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
    // algID, new BIT_STRING(encodedPublicValue, 0) );
    // 
    // return PK11PubKey.fromSPKI( ASN1Util.encode(spki) );
    // 
    // use the following for EC keys in 1.4.2
    } else if (keySpec instanceof X509EncodedKeySpec) {
        // 
        // SubjectPublicKeyInfo
        // 
        X509EncodedKeySpec spec = (X509EncodedKeySpec) keySpec;
        return PK11PubKey.fromSPKI(spec.getEncoded());
    }
    throw new InvalidKeySpecException("Unsupported KeySpec type: " + keySpec.getClass().getName());
}
Also used : SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) OBJECT_IDENTIFIER(org.mozilla.jss.asn1.OBJECT_IDENTIFIER) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SubjectPublicKeyInfo(org.mozilla.jss.pkix.primitive.SubjectPublicKeyInfo) BIT_STRING(org.mozilla.jss.asn1.BIT_STRING) INTEGER(org.mozilla.jss.asn1.INTEGER) DSAPublicKeySpec(java.security.spec.DSAPublicKeySpec) AlgorithmIdentifier(org.mozilla.jss.pkix.primitive.AlgorithmIdentifier)

Example 5 with AlgorithmIdentifier

use of org.mozilla.jss.pkix.primitive.AlgorithmIdentifier in project jss by dogtagpki.

the class SignerInfo method verifyWithAuthenticatedAttributes.

/**
 * Verifies a SignerInfo with authenticated attributes.  If authenticated
 * attributes are present, then two particular attributes must
 * be present: <ul>
 * <li>PKCS #9 Content-Type, the type of content that is being signed.
 *      This must match the contentType parameter.
 * <li>PKCS #9 Message-Digest, the digest of the content that is being
 *      signed. This must match the messageDigest parameter.
 * </ul>
 * After these two attributes are verified to be both present and correct,
 * the encryptedDigest field of the SignerInfo is verified to be the
 * signature of the contents octets of the DER encoding of the
 * authenticatedAttributes field.
 */
private void verifyWithAuthenticatedAttributes(byte[] messageDigest, OBJECT_IDENTIFIER contentType, PublicKey pubkey) throws NotInitializedException, NoSuchAlgorithmException, InvalidKeyException, TokenException, SignatureException {
    int numAttrib = authenticatedAttributes.size();
    if (numAttrib < 2) {
        throw new SignatureException("At least two authenticated attributes must be present:" + " content-type and message-digest");
    }
    // go through the authenticated attributes, verifying the
    // interesting ones
    boolean foundContentType = false;
    boolean foundMessageDigest = false;
    for (int i = 0; i < numAttrib; i++) {
        if (!(authenticatedAttributes.elementAt(i) instanceof Attribute)) {
            throw new SignatureException("Element of authenticatedAttributes is not an Attribute");
        }
        Attribute attrib = (Attribute) authenticatedAttributes.elementAt(i);
        if (attrib.getType().equals(CONTENT_TYPE)) {
            // content-type.  Compare with what was passed in.
            SET vals = attrib.getValues();
            if (vals.size() != 1) {
                throw new SignatureException("Content-Type attribute " + " does not have exactly one value");
            }
            ASN1Value val = vals.elementAt(0);
            OBJECT_IDENTIFIER ctype;
            try {
                if (val instanceof OBJECT_IDENTIFIER) {
                    ctype = (OBJECT_IDENTIFIER) val;
                } else if (val instanceof ANY) {
                    ctype = (OBJECT_IDENTIFIER) ((ANY) val).decodeWith(OBJECT_IDENTIFIER.getTemplate());
                } else {
                    // what the heck is it? not what it's supposed to be
                    throw new InvalidBERException("Content-Type authenticated attribute has unexpected" + " content type");
                }
            } catch (InvalidBERException e) {
                throw new SignatureException("Content-Type authenticated attribute does not have " + "OBJECT IDENTIFIER value");
            }
            // contentType parameter
            if (!ctype.equals(contentType)) {
                throw new SignatureException("Content-type in authenticated attributes does not " + "match content-type being verified");
            }
            // content type is A-OK
            foundContentType = true;
        } else if (attrib.getType().equals(MESSAGE_DIGEST)) {
            SET vals = attrib.getValues();
            if (vals.size() != 1) {
                throw new SignatureException("Message-digest attribute does not have" + " exactly one value");
            }
            ASN1Value val = vals.elementAt(0);
            byte[] mdigest;
            try {
                if (val instanceof OCTET_STRING) {
                    mdigest = ((OCTET_STRING) val).toByteArray();
                } else if (val instanceof ANY) {
                    OCTET_STRING os;
                    os = (OCTET_STRING) ((ANY) val).decodeWith(OCTET_STRING.getTemplate());
                    mdigest = os.toByteArray();
                } else {
                    // what the heck is it? not what it's supposed to be
                    throw new InvalidBERException("Content-Type authenticated attribute has unexpected" + " content type");
                }
            } catch (InvalidBERException e) {
                throw new SignatureException("Message-digest attribute does not" + " have OCTET STRING value");
            }
            // message digest being verified
            if (!byteArraysAreSame(mdigest, messageDigest)) {
                throw new SignatureException("Message-digest attribute does not" + " match message digest being verified");
            }
            // message digest is A-OK
            foundMessageDigest = true;
        }
    // we don't care about other attributes
    }
    if (!foundContentType) {
        throw new SignatureException("Authenticated attributes does not contain" + " PKCS #9 content-type attribute");
    }
    if (!foundMessageDigest) {
        throw new SignatureException("Authenticate attributes does not contain" + " PKCS #9 message-digest attribute");
    }
    SignatureAlgorithm sigAlg = SignatureAlgorithm.fromOID(digestEncryptionAlgorithm.getOID());
    // All the authenticated attributes are present and correct.
    // Now verify the signature.
    CryptoToken token = CryptoManager.getInstance().getInternalCryptoToken();
    Signature sig = token.getSignatureContext(sigAlg);
    sig.initVerify(pubkey);
    // verify the contents octets of the DER encoded authenticated attribs
    byte[] toBeDigested;
    toBeDigested = ASN1Util.encode(authenticatedAttributes);
    MessageDigest md = MessageDigest.getInstance(DigestAlgorithm.fromOID(digestAlgorithm.getOID()).toString());
    byte[] digest = md.digest(toBeDigested);
    byte[] toBeVerified;
    if (sigAlg.getRawAlg() == SignatureAlgorithm.RSASignature) {
        // create DigestInfo structure
        SEQUENCE digestInfo = new SEQUENCE();
        digestInfo.addElement(new AlgorithmIdentifier(digestAlgorithm.getOID(), null));
        digestInfo.addElement(new OCTET_STRING(digest));
        toBeVerified = ASN1Util.encode(digestInfo);
    } else {
        toBeVerified = digest;
    }
    sig.update(toBeVerified);
    if (!sig.verify(encryptedDigest.toByteArray())) {
        // signature is invalid
        throw new SignatureException("encryptedDigest was not the correct" + " signature of the contents octets of the DER-encoded" + " authenticated attributes");
    }
// SUCCESSFULLY VERIFIED
}
Also used : SET(org.mozilla.jss.asn1.SET) CryptoToken(org.mozilla.jss.crypto.CryptoToken) OBJECT_IDENTIFIER(org.mozilla.jss.asn1.OBJECT_IDENTIFIER) SignatureAlgorithm(org.mozilla.jss.crypto.SignatureAlgorithm) SignatureException(java.security.SignatureException) ANY(org.mozilla.jss.asn1.ANY) AlgorithmIdentifier(org.mozilla.jss.pkix.primitive.AlgorithmIdentifier) InvalidBERException(org.mozilla.jss.asn1.InvalidBERException) ASN1Value(org.mozilla.jss.asn1.ASN1Value) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) Signature(org.mozilla.jss.crypto.Signature) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) MessageDigest(java.security.MessageDigest)

Aggregations

AlgorithmIdentifier (org.mozilla.jss.pkix.primitive.AlgorithmIdentifier)11 CryptoToken (org.mozilla.jss.crypto.CryptoToken)6 OCTET_STRING (org.mozilla.jss.asn1.OCTET_STRING)5 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)4 INTEGER (org.mozilla.jss.asn1.INTEGER)4 SEQUENCE (org.mozilla.jss.asn1.SEQUENCE)4 Cipher (org.mozilla.jss.crypto.Cipher)4 EncryptionAlgorithm (org.mozilla.jss.crypto.EncryptionAlgorithm)4 IVParameterSpec (org.mozilla.jss.crypto.IVParameterSpec)4 KeyGenerator (org.mozilla.jss.crypto.KeyGenerator)4 PBEKeyGenParams (org.mozilla.jss.crypto.PBEKeyGenParams)4 SymmetricKey (org.mozilla.jss.crypto.SymmetricKey)4 PBEParameter (org.mozilla.jss.pkix.primitive.PBEParameter)4 SubjectPublicKeyInfo (org.mozilla.jss.pkix.primitive.SubjectPublicKeyInfo)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 SignatureException (java.security.SignatureException)3 ASN1Value (org.mozilla.jss.asn1.ASN1Value)3 Signature (org.mozilla.jss.crypto.Signature)3 SignatureAlgorithm (org.mozilla.jss.crypto.SignatureAlgorithm)3 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)2