Search in sources :

Example 6 with AlgorithmIdentifier

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

the class EncryptedContentInfo method createPBE.

// /////////////////////////////////////////////////////////////////////
// Crypto shortcuts
// /////////////////////////////////////////////////////////////////////
/**
 * Creates a new EncryptedContentInfo, where the data is encrypted
 * with a password-based key.
 *
 * @param pbeAlg The algorithm for generating a symmetric key from
 *      a password, salt, and iteration count.
 * @param password The password to use in generating the key.
 * @param salt The salt to use in generating the key.
 * @param iterationCount The number of hashing iterations to perform
 *      while generating the key.
 * @param charToByteConverter The mechanism for converting the characters
 *      in the password into bytes.  If null, the default mechanism
 *      will be used, which is UTF8.
 * @param toBeEncrypted The bytes to be encrypted and stored in the
 *      EncryptedContentInfo. Before they are encrypted, they will be
 *      padded using PKCS padding.
 */
public static EncryptedContentInfo createPBE(PBEAlgorithm pbeAlg, Password password, byte[] salt, int iterationCount, KeyGenerator.CharToByteConverter charToByteConverter, byte[] toBeEncrypted) throws NotInitializedException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException, TokenException, CharConversionException {
    try {
        CryptoManager cman = CryptoManager.getInstance();
        // generate key
        CryptoToken token = cman.getInternalCryptoToken();
        KeyGenerator kg = token.getKeyGenerator(pbeAlg);
        PBEKeyGenParams pbekgParams = new PBEKeyGenParams(password, salt, iterationCount);
        if (charToByteConverter != null) {
            kg.setCharToByteConverter(charToByteConverter);
        }
        kg.initialize(pbekgParams);
        SymmetricKey key = kg.generate();
        // generate IV
        EncryptionAlgorithm encAlg = pbeAlg.getEncryptionAlg();
        AlgorithmParameterSpec params = null;
        Class<?>[] paramClasses = encAlg.getParameterClasses();
        for (int i = 0; i < paramClasses.length; i++) {
            if (paramClasses[i].equals(javax.crypto.spec.IvParameterSpec.class)) {
                params = new IVParameterSpec(kg.generatePBE_IV());
                break;
            } else if (paramClasses[i].equals(RC2ParameterSpec.class)) {
                params = new RC2ParameterSpec(key.getStrength(), kg.generatePBE_IV());
                break;
            }
        }
        // perform encryption
        Cipher cipher = token.getCipherContext(encAlg);
        cipher.initEncrypt(key, params);
        byte[] encrypted = cipher.doFinal(Cipher.pad(toBeEncrypted, encAlg.getBlockSize()));
        // make encryption algorithm identifier
        PBEParameter pbeParam = new PBEParameter(salt, iterationCount);
        AlgorithmIdentifier encAlgID = new AlgorithmIdentifier(pbeAlg.toOID(), pbeParam);
        // create EncryptedContentInfo
        EncryptedContentInfo encCI = new EncryptedContentInfo(ContentInfo.DATA, encAlgID, new OCTET_STRING(encrypted));
        return encCI;
    } catch (IllegalBlockSizeException e) {
        throw new RuntimeException("IllegalBlockSizeException in EncryptedContentInfo" + ".createPBE: " + e.getMessage(), e);
    } catch (BadPaddingException e) {
        throw new RuntimeException("BadPaddingException in EncryptedContentInfo" + ".createPBE: " + e.getMessage(), e);
    }
}
Also used : PBEParameter(org.mozilla.jss.pkix.primitive.PBEParameter) CryptoToken(org.mozilla.jss.crypto.CryptoToken) IVParameterSpec(org.mozilla.jss.crypto.IVParameterSpec) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey) IllegalBlockSizeException(org.mozilla.jss.crypto.IllegalBlockSizeException) CryptoManager(org.mozilla.jss.CryptoManager) BadPaddingException(javax.crypto.BadPaddingException) AlgorithmIdentifier(org.mozilla.jss.pkix.primitive.AlgorithmIdentifier) PBEKeyGenParams(org.mozilla.jss.crypto.PBEKeyGenParams) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) EncryptionAlgorithm(org.mozilla.jss.crypto.EncryptionAlgorithm) RC2ParameterSpec(javax.crypto.spec.RC2ParameterSpec) Cipher(org.mozilla.jss.crypto.Cipher) KeyGenerator(org.mozilla.jss.crypto.KeyGenerator) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 7 with AlgorithmIdentifier

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

the class EncryptedContentInfo method createPBE.

// /////////////////////////////////////////////////////////////////////
// Crypto shortcuts
// /////////////////////////////////////////////////////////////////////
/**
 * Creates a new EncryptedContentInfo, where the data is encrypted
 * with a password-based key.
 *
 * @param pbeAlg The algorithm for generating a symmetric key from
 *      a password, salt, and iteration count.
 * @param password The password to use in generating the key.
 * @param salt The salt to use in generating the key.
 * @param iterationCount The number of hashing iterations to perform
 *      while generating the key.
 * @param charToByteConverter The mechanism for converting the characters
 *      in the password into bytes.  If null, the default mechanism
 *      will be used, which is UTF8.
 * @param toBeEncrypted The bytes to be encrypted and stored in the
 *      EncryptedContentInfo. Before they are encrypted, they will be
 *      padded using PKCS padding.
 */
public static EncryptedContentInfo createPBE(PBEAlgorithm pbeAlg, Password password, byte[] salt, int iterationCount, KeyGenerator.CharToByteConverter charToByteConverter, byte[] toBeEncrypted) throws NotInitializedException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException, TokenException, CharConversionException {
    try {
        CryptoManager cman = CryptoManager.getInstance();
        // generate key
        CryptoToken token = cman.getInternalCryptoToken();
        KeyGenerator kg = token.getKeyGenerator(pbeAlg);
        PBEKeyGenParams pbekgParams = new PBEKeyGenParams(password, salt, iterationCount);
        if (charToByteConverter != null) {
            kg.setCharToByteConverter(charToByteConverter);
        }
        kg.initialize(pbekgParams);
        SymmetricKey key = kg.generate();
        // generate IV
        EncryptionAlgorithm encAlg = pbeAlg.getEncryptionAlg();
        AlgorithmParameterSpec params = null;
        Class<?>[] paramClasses = encAlg.getParameterClasses();
        for (int i = 0; i < paramClasses.length; i++) {
            if (paramClasses[i].equals(IVParameterSpec.class)) {
                params = new IVParameterSpec(kg.generatePBE_IV());
                break;
            }
        }
        // perform encryption
        Cipher cipher = token.getCipherContext(encAlg);
        cipher.initEncrypt(key, params);
        byte[] encrypted = cipher.doFinal(Cipher.pad(toBeEncrypted, encAlg.getBlockSize()));
        // make encryption algorithm identifier
        PBEParameter pbeParam = new PBEParameter(salt, iterationCount);
        AlgorithmIdentifier encAlgID = new AlgorithmIdentifier(pbeAlg.toOID(), pbeParam);
        // create EncryptedContentInfo
        EncryptedContentInfo encCI = new EncryptedContentInfo(ContentInfo.DATA, encAlgID, new OCTET_STRING(encrypted));
        return encCI;
    } catch (IllegalBlockSizeException e) {
        throw new RuntimeException("IllegalBlockSizeException in EncryptedContentInfo" + ".createPBE: " + e.getMessage(), e);
    } catch (BadPaddingException e) {
        throw new RuntimeException("BadPaddingException in EncryptedContentInfo" + ".createPBE: " + e.getMessage(), e);
    }
}
Also used : PBEParameter(org.mozilla.jss.pkix.primitive.PBEParameter) CryptoToken(org.mozilla.jss.crypto.CryptoToken) IVParameterSpec(org.mozilla.jss.crypto.IVParameterSpec) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey) IllegalBlockSizeException(org.mozilla.jss.crypto.IllegalBlockSizeException) CryptoManager(org.mozilla.jss.CryptoManager) BadPaddingException(javax.crypto.BadPaddingException) AlgorithmIdentifier(org.mozilla.jss.pkix.primitive.AlgorithmIdentifier) PBEKeyGenParams(org.mozilla.jss.crypto.PBEKeyGenParams) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) EncryptionAlgorithm(org.mozilla.jss.crypto.EncryptionAlgorithm) Cipher(org.mozilla.jss.crypto.Cipher) KeyGenerator(org.mozilla.jss.crypto.KeyGenerator) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 8 with AlgorithmIdentifier

use of org.mozilla.jss.pkix.primitive.AlgorithmIdentifier 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());
    try {
        // 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;
            } else if (paramClasses[i].equals(RC2ParameterSpec.class)) {
                algParams = new RC2ParameterSpec(key.getStrength(), kg.generatePBE_IV());
                break;
            }
        }
        // perform the decryption
        Cipher cipher = token.getCipherContext(encAlg);
        cipher.initDecrypt(key, algParams);
        return Cipher.unPad(cipher.doFinal(encryptedContent.toByteArray()));
    } finally {
        kgp.clear();
    }
}
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) RC2ParameterSpec(javax.crypto.spec.RC2ParameterSpec) Cipher(org.mozilla.jss.crypto.Cipher) KeyGenerator(org.mozilla.jss.crypto.KeyGenerator) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 9 with AlgorithmIdentifier

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

the class SignerInfo method verifyWithoutAuthenticatedAttributes.

/**
 * Verifies that the message digest passed in, when encrypted with the
 * given public key, matches the encrypted digest in the SignerInfo.
 */
private void verifyWithoutAuthenticatedAttributes(byte[] messageDigest, OBJECT_IDENTIFIER contentType, PublicKey pubkey) throws NotInitializedException, NoSuchAlgorithmException, InvalidKeyException, TokenException, SignatureException {
    if (!contentType.equals(ContentInfo.DATA)) {
        // to go into authenticatedAttributes.
        throw new SignatureException("Content-Type is not DATA, but there are" + " no authenticated attributes");
    }
    SignatureAlgorithm sigAlg = SignatureAlgorithm.fromOID(digestEncryptionAlgorithm.getOID());
    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(messageDigest));
        toBeVerified = ASN1Util.encode(digestInfo);
    } else {
        toBeVerified = messageDigest;
    }
    CryptoToken token = CryptoManager.getInstance().getInternalCryptoToken();
    Signature sig = token.getSignatureContext(sigAlg);
    sig.initVerify(pubkey);
    sig.update(toBeVerified);
    if (sig.verify(encryptedDigest.toByteArray())) {
        // success
        return;
    } else {
        throw new SignatureException("Encrypted message digest parameter does not " + "match encrypted digest in SignerInfo");
    }
}
Also used : OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) CryptoToken(org.mozilla.jss.crypto.CryptoToken) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) Signature(org.mozilla.jss.crypto.Signature) SignatureAlgorithm(org.mozilla.jss.crypto.SignatureAlgorithm) SignatureException(java.security.SignatureException) AlgorithmIdentifier(org.mozilla.jss.pkix.primitive.AlgorithmIdentifier)

Example 10 with AlgorithmIdentifier

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

the class KeyFactorySpi1_2 method engineGeneratePrivate.

/**
 * We don't support RSAPrivateKeySpec because it doesn't have enough
 * information. You need to provide an RSAPrivateCrtKeySpec.
 */
@Override
protected java.security.PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException {
    try {
        if (keySpec instanceof RSAPrivateCrtKeySpec) {
            // 
            // PKCS #1 RSAPrivateKey
            // 
            RSAPrivateCrtKeySpec spec = (RSAPrivateCrtKeySpec) keySpec;
            SEQUENCE privKey = new SEQUENCE();
            // version
            privKey.addElement(new INTEGER(0));
            privKey.addElement(new INTEGER(spec.getModulus()));
            privKey.addElement(new INTEGER(spec.getPublicExponent()));
            privKey.addElement(new INTEGER(spec.getPrivateExponent()));
            privKey.addElement(new INTEGER(spec.getPrimeP()));
            privKey.addElement(new INTEGER(spec.getPrimeQ()));
            privKey.addElement(new INTEGER(spec.getPrimeExponentP()));
            privKey.addElement(new INTEGER(spec.getPrimeExponentQ()));
            privKey.addElement(new INTEGER(spec.getCrtCoefficient()));
            AlgorithmIdentifier algID = new AlgorithmIdentifier(PrivateKey.RSA.toOID(), null);
            OCTET_STRING encodedPrivKey = new OCTET_STRING(ASN1Util.encode(privKey));
            PrivateKeyInfo pki = new PrivateKeyInfo(// version
            new INTEGER(0), algID, encodedPrivKey, // OPTIONAL SET OF Attribute
            (SET) null);
            return PK11PrivKey.fromPrivateKeyInfo(ASN1Util.encode(pki), TokenSupplierManager.getTokenSupplier().getThreadToken());
        } else if (keySpec instanceof DSAPrivateKeySpec) {
            DSAPrivateKeySpec spec = (DSAPrivateKeySpec) keySpec;
            SEQUENCE pqgParams = new SEQUENCE();
            pqgParams.addElement(new INTEGER(spec.getP()));
            pqgParams.addElement(new INTEGER(spec.getQ()));
            pqgParams.addElement(new INTEGER(spec.getG()));
            AlgorithmIdentifier algID = new AlgorithmIdentifier(PrivateKey.DSA.toOID(), pqgParams);
            OCTET_STRING privateKey = new OCTET_STRING(ASN1Util.encode(new INTEGER(spec.getX())));
            PrivateKeyInfo pki = new PrivateKeyInfo(// version
            new INTEGER(0), algID, privateKey, // OPTIONAL SET OF Attribute
            null);
            // Derive the public key from the private key
            BigInteger y = spec.getG().modPow(spec.getX(), spec.getP());
            byte[] yBA = y.toByteArray();
            // we need to chop off a leading zero byte
            if (y.bitLength() % 8 == 0) {
                byte[] newBA = new byte[yBA.length - 1];
                assert (newBA.length >= 0);
                System.arraycopy(yBA, 1, newBA, 0, newBA.length);
                yBA = newBA;
            }
            return PK11PrivKey.fromPrivateKeyInfo(ASN1Util.encode(pki), TokenSupplierManager.getTokenSupplier().getThreadToken(), yBA);
        } else if (keySpec instanceof PKCS8EncodedKeySpec) {
            return PK11PrivKey.fromPrivateKeyInfo((PKCS8EncodedKeySpec) keySpec, TokenSupplierManager.getTokenSupplier().getThreadToken());
        }
        throw new InvalidKeySpecException("Unsupported KeySpec type: " + keySpec.getClass().getName());
    } catch (TokenException te) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        te.printStackTrace(pw);
        throw new InvalidKeySpecException("TokenException: " + sw.toString());
    }
}
Also used : RSAPrivateCrtKeySpec(java.security.spec.RSAPrivateCrtKeySpec) AlgorithmIdentifier(org.mozilla.jss.pkix.primitive.AlgorithmIdentifier) DSAPrivateKeySpec(java.security.spec.DSAPrivateKeySpec) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) StringWriter(java.io.StringWriter) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) TokenException(org.mozilla.jss.crypto.TokenException) BigInteger(java.math.BigInteger) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) PrivateKeyInfo(org.mozilla.jss.pkix.primitive.PrivateKeyInfo) INTEGER(org.mozilla.jss.asn1.INTEGER) PrintWriter(java.io.PrintWriter)

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