Search in sources :

Example 16 with InvalidBERException

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

the class EncryptedPrivateKeyInfo method decrypt.

/**
 * Decrypts an EncryptedPrivateKeyInfo that was encrypted with a PBE
 *  algorithm.  The algorithm and its parameters are extracted from
 *  the EncryptedPrivateKeyInfo.
 *
 * @param pass The password to use to generate the PBE key.
 * @param charToByteConverter The converter to change the password
 *      characters to bytes.  If null, the default conversion is used.
 */
public PrivateKeyInfo decrypt(Password pass, KeyGenerator.CharToByteConverter charToByteConverter) throws NotInitializedException, NoSuchAlgorithmException, InvalidBERException, InvalidKeyException, InvalidAlgorithmParameterException, TokenException, IllegalBlockSizeException, BadPaddingException, CharConversionException {
    // get the key gen parameters
    AlgorithmIdentifier algid = encryptionAlgorithm;
    KeyGenAlgorithm kgAlg = KeyGenAlgorithm.fromOID(algid.getOID());
    if (!(kgAlg instanceof PBEAlgorithm)) {
        throw new NoSuchAlgorithmException("KeyGenAlgorithm is not a " + "PBE algorithm");
    }
    ASN1Value params = algid.getParameters();
    if (params == null) {
        throw new InvalidAlgorithmParameterException("PBE algorithms require parameters");
    }
    PBEParameter pbeParams;
    if (params instanceof PBEParameter) {
        pbeParams = (PBEParameter) params;
    } else {
        byte[] encodedParams = ASN1Util.encode(params);
        pbeParams = (PBEParameter) ASN1Util.decode(PBEParameter.getTemplate(), encodedParams);
    }
    PBEKeyGenParams kgp = new PBEKeyGenParams(pass, pbeParams.getSalt(), pbeParams.getIterations());
    // compute the key and IV
    CryptoToken token = CryptoManager.getInstance().getInternalCryptoToken();
    KeyGenerator kg = token.getKeyGenerator(kgAlg);
    if (charToByteConverter != null) {
        kg.setCharToByteConverter(charToByteConverter);
    }
    kg.initialize(kgp);
    SymmetricKey key = kg.generate();
    // compute algorithm parameters
    EncryptionAlgorithm encAlg = ((PBEAlgorithm) kgAlg).getEncryptionAlg();
    AlgorithmParameterSpec algParams = null;
    Class<?>[] paramClasses = encAlg.getParameterClasses();
    for (int i = 0; i < paramClasses.length; i++) {
        if (paramClasses[i].equals(javax.crypto.spec.IvParameterSpec.class)) {
            algParams = new IVParameterSpec(kg.generatePBE_IV());
            break;
        }
    }
    // perform the decryption
    Cipher cipher = token.getCipherContext(encAlg);
    cipher.initDecrypt(key, algParams);
    byte[] decrypted = Cipher.unPad(cipher.doFinal(encryptedData.toByteArray()));
    return (PrivateKeyInfo) ASN1Util.decode(PrivateKeyInfo.getTemplate(), decrypted);
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CryptoToken(org.mozilla.jss.crypto.CryptoToken) IVParameterSpec(org.mozilla.jss.crypto.IVParameterSpec) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) PBEKeyGenParams(org.mozilla.jss.crypto.PBEKeyGenParams) ASN1Value(org.mozilla.jss.asn1.ASN1Value) PBEAlgorithm(org.mozilla.jss.crypto.PBEAlgorithm) KeyGenAlgorithm(org.mozilla.jss.crypto.KeyGenAlgorithm) EncryptionAlgorithm(org.mozilla.jss.crypto.EncryptionAlgorithm) Cipher(org.mozilla.jss.crypto.Cipher) KeyGenerator(org.mozilla.jss.crypto.KeyGenerator) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 17 with InvalidBERException

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

the class SignerInfo method verifyWithSignedAttributes.

/**
 * Verifies a SignerInfo with signed attributes.  If signed
 * 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
 * signedAttributes field.
 */
private void verifyWithSignedAttributes(byte[] messageDigest, OBJECT_IDENTIFIER contentType, PublicKey pubkey) throws NotInitializedException, NoSuchAlgorithmException, InvalidKeyException, TokenException, SignatureException {
    int numAttrib = signedAttributes.size();
    if (numAttrib < 2) {
        throw new SignatureException("At least two signed attributes must be present:" + " content-type and message-digest");
    }
    // go through the signed attributes, verifying the
    // interesting ones
    boolean foundContentType = false;
    boolean foundMessageDigest = false;
    for (int i = 0; i < numAttrib; i++) {
        if (!(signedAttributes.elementAt(i) instanceof Attribute)) {
            throw new SignatureException("Element of signedAttributes is not an Attribute");
        }
        Attribute attrib = (Attribute) signedAttributes.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 signed attribute has unexpected" + " content type");
                }
            } catch (InvalidBERException e) {
                throw new SignatureException("Content-Type signed attribute does not have " + "OBJECT IDENTIFIER value");
            }
            // contentType parameter
            if (!ctype.equals(contentType)) {
                throw new SignatureException("Content-type in signed 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 signed 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("Signed attributes does not contain" + " PKCS #9 content-type attribute");
    }
    if (!foundMessageDigest) {
        throw new SignatureException("Signed attributes does not contain" + " PKCS #9 message-digest attribute");
    }
    SignatureAlgorithm sigAlg = SignatureAlgorithm.fromOID(digestEncryptionAlgorithm.getOID());
    // All the signed attributes are present and correct.
    // Now verify the signature.
    CryptoToken token = CryptoManager.getInstance().getInternalCryptoToken();
    Signature sig;
    // verify the contents octets of the DER encoded signed attribs
    byte[] encoding = ASN1Util.encode(signedAttributes);
    byte[] toBeVerified;
    if (sigAlg.getRawAlg() == SignatureAlgorithm.RSASignature) {
        // create DigestInfo structure
        SEQUENCE digestInfo = createDigestInfo(encoding, true);
        toBeVerified = ASN1Util.encode(digestInfo);
        sig = token.getSignatureContext(SignatureAlgorithm.RSASignature);
    } else {
        toBeVerified = encoding;
        sig = token.getSignatureContext(sigAlg);
    }
    sig.initVerify(pubkey);
    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" + " signed attributes");
    }
// SUCCESSFULLY VERIFIED
}
Also used : SET(org.mozilla.jss.asn1.SET) CryptoToken(org.mozilla.jss.crypto.CryptoToken) Attribute(org.mozilla.jss.pkix.primitive.Attribute) OBJECT_IDENTIFIER(org.mozilla.jss.asn1.OBJECT_IDENTIFIER) SignatureAlgorithm(org.mozilla.jss.crypto.SignatureAlgorithm) SignatureException(java.security.SignatureException) ANY(org.mozilla.jss.asn1.ANY) 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)

Example 18 with InvalidBERException

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

the class EncryptedContentInfo method decrypt.

/**
 * Decrypts the content of an EncryptedContentInfo encrypted with a
 * PBE key.
 *
 * @param pass The password to use in generating the PBE decryption key.
 * @param charToByteConverter The converter for converting the password
 *      characters into bytes.  May be null to use the default.
 * @return The decrypted contents of the EncryptedContentInfo. The contents
 *      are first unpadded using the PKCS padding mechanism.
 */
public byte[] decrypt(Password pass, KeyGenerator.CharToByteConverter charToByteConverter) throws IllegalStateException, NotInitializedException, NoSuchAlgorithmException, InvalidBERException, IOException, InvalidKeyException, InvalidAlgorithmParameterException, TokenException, IllegalBlockSizeException, BadPaddingException {
    if (encryptedContent == null) {
        return null;
    }
    // get the key gen parameters
    AlgorithmIdentifier algid = contentEncryptionAlgorithm;
    KeyGenAlgorithm kgAlg = KeyGenAlgorithm.fromOID(algid.getOID());
    if (!(kgAlg instanceof PBEAlgorithm)) {
        throw new NoSuchAlgorithmException("KeyGenAlgorithm is not a" + " PBE algorithm");
    }
    ASN1Value params = algid.getParameters();
    if (params == null) {
        throw new InvalidAlgorithmParameterException("PBE algorithms require parameters");
    }
    PBEParameter pbeParams;
    if (params instanceof PBEParameter) {
        pbeParams = (PBEParameter) params;
    } else {
        byte[] encodedParams = ASN1Util.encode(params);
        pbeParams = (PBEParameter) ASN1Util.decode(PBEParameter.getTemplate(), encodedParams);
    }
    PBEKeyGenParams kgp = new PBEKeyGenParams(pass, pbeParams.getSalt(), pbeParams.getIterations());
    // compute the key and IV
    CryptoToken token = CryptoManager.getInstance().getInternalCryptoToken();
    KeyGenerator kg = token.getKeyGenerator(kgAlg);
    if (charToByteConverter != null) {
        kg.setCharToByteConverter(charToByteConverter);
    }
    kg.initialize(kgp);
    SymmetricKey key = kg.generate();
    // compute algorithm parameters
    EncryptionAlgorithm encAlg = ((PBEAlgorithm) kgAlg).getEncryptionAlg();
    AlgorithmParameterSpec algParams = null;
    Class<?>[] paramClasses = encAlg.getParameterClasses();
    for (int i = 0; i < paramClasses.length; i++) {
        if (paramClasses[i].equals(javax.crypto.spec.IvParameterSpec.class)) {
            algParams = new IVParameterSpec(kg.generatePBE_IV());
            break;
        }
    }
    // perform the decryption
    Cipher cipher = token.getCipherContext(encAlg);
    cipher.initDecrypt(key, algParams);
    return Cipher.unPad(cipher.doFinal(encryptedContent.toByteArray()));
}
Also used : PBEParameter(org.mozilla.jss.pkix.primitive.PBEParameter) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CryptoToken(org.mozilla.jss.crypto.CryptoToken) IVParameterSpec(org.mozilla.jss.crypto.IVParameterSpec) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmIdentifier(org.mozilla.jss.pkix.primitive.AlgorithmIdentifier) PBEKeyGenParams(org.mozilla.jss.crypto.PBEKeyGenParams) ASN1Value(org.mozilla.jss.asn1.ASN1Value) PBEAlgorithm(org.mozilla.jss.crypto.PBEAlgorithm) KeyGenAlgorithm(org.mozilla.jss.crypto.KeyGenAlgorithm) EncryptionAlgorithm(org.mozilla.jss.crypto.EncryptionAlgorithm) Cipher(org.mozilla.jss.crypto.Cipher) KeyGenerator(org.mozilla.jss.crypto.KeyGenerator) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Aggregations

InvalidBERException (org.mozilla.jss.asn1.InvalidBERException)11 ANY (org.mozilla.jss.asn1.ANY)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 OCTET_STRING (org.mozilla.jss.asn1.OCTET_STRING)6 SEQUENCE (org.mozilla.jss.asn1.SEQUENCE)6 CryptoToken (org.mozilla.jss.crypto.CryptoToken)6 ASN1Value (org.mozilla.jss.asn1.ASN1Value)5 DerOutputStream (org.mozilla.jss.netscape.security.util.DerOutputStream)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 EncryptionAlgorithm (org.mozilla.jss.crypto.EncryptionAlgorithm)4 SymmetricKey (org.mozilla.jss.crypto.SymmetricKey)4 IOException (java.io.IOException)3 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)3 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)3 OBJECT_IDENTIFIER (org.mozilla.jss.asn1.OBJECT_IDENTIFIER)3 SET (org.mozilla.jss.asn1.SET)3 Cipher (org.mozilla.jss.crypto.Cipher)3 IVParameterSpec (org.mozilla.jss.crypto.IVParameterSpec)3 KeyGenAlgorithm (org.mozilla.jss.crypto.KeyGenAlgorithm)3 KeyGenerator (org.mozilla.jss.crypto.KeyGenerator)3