Search in sources :

Example 16 with TokenException

use of org.mozilla.jss.crypto.TokenException in project jss by dogtagpki.

the class PFX method verifyAuthSafes.

/**
 * Verifies the HMAC on the authenticated safes, using the password
 * provided.
 *
 * @param password The password to use to compute the HMAC.
 * @param reason If supplied, the reason for the verification failure
 *      will be appended to this StringBuffer.
 * @return true if the MAC verifies correctly, false otherwise. If
 *      this PFX does not contain a MacData, returns false.
 */
public boolean verifyAuthSafes(Password password, StringBuffer reason) throws NotInitializedException {
    try {
        if (reason == null) {
            // this is just so we don't get a null pointer exception
            reason = new StringBuffer();
        }
        if (macData == null) {
            reason.append("No MAC present in PFX");
            return false;
        }
        if (encodedAuthSafes == null) {
            // We weren't decoded from a template, we were constructed,
            // so just verify the encoding of the AuthSafes provided to
            // the constructor.
            encodedAuthSafes = ASN1Util.encode(authSafes);
        }
        // create a new MacData based on the encoded Auth Safes
        DigestInfo macDataMac = macData.getMac();
        MacData testMac = new MacData(password, macData.getMacSalt().toByteArray(), macData.getMacIterationCount().intValue(), encodedAuthSafes);
        if (testMac.getMac().equals(macDataMac)) {
            return true;
        } else {
            reason.append("Digests do not match");
            return false;
        }
    } catch (java.security.DigestException e) {
        e.printStackTrace();
        reason.append("A DigestException occurred");
        return false;
    } catch (TokenException e) {
        reason.append("A TokenException occurred");
        return false;
    } catch (CharConversionException e) {
        reason.append("An exception occurred converting the password from chars to bytes");
        return false;
    }
}
Also used : DigestInfo(org.mozilla.jss.pkcs7.DigestInfo) TokenException(org.mozilla.jss.crypto.TokenException) DigestException(java.security.DigestException) CharConversionException(java.io.CharConversionException)

Example 17 with TokenException

use of org.mozilla.jss.crypto.TokenException in project jss by dogtagpki.

the class PK11KeyPairGenerator method generateKeyPair.

/**
 * Generates a key pair on a token. Uses parameters if they were passed
 * in through a call to <code>initialize</code>, otherwise uses defaults.
 * @return
 * @throws TokenException
 */
@Override
public KeyPair generateKeyPair() throws TokenException {
    if (algorithm == KeyPairAlgorithm.RSA) {
        if (params != null) {
            RSAKeyGenParameterSpec rsaparams = (RSAKeyGenParameterSpec) params;
            if (rsaparams.getKeysize() < Policy.RSA_MINIMUM_KEY_SIZE) {
                String msg = "unsafe RSA key size of ";
                msg += rsaparams.getKeysize() + ". Policy.RSA_MINIMUM_KEY_SIZE ";
                msg += "dictates a minimum of " + Policy.RSA_MINIMUM_KEY_SIZE;
                if (Policy.ENFORCING_KEY_SIZES) {
                    throw new TokenException("Disallowing " + msg);
                } else {
                    logger.warn("Ignored jss.crypto.Policy violation: " + msg);
                }
            }
            if (rsaparams.getPublicExponent().longValue() < Policy.RSA_MINIMUM_PUBLIC_EXPONENT.longValue()) {
                String msg = "unsafe RSA exponent of ";
                msg += rsaparams.getPublicExponent().longValue() + ". ";
                msg += "Policy.RSA_MINIMUM_PUBLIC_EXPONENT dictates a minimum of ";
                msg += Policy.RSA_MINIMUM_PUBLIC_EXPONENT.longValue();
                if (Policy.ENFORCING_KEY_SIZES) {
                    throw new TokenException("Disallowing " + msg);
                } else {
                    logger.warn("Ignored jss.crypto.Policy violation: " + msg);
                }
            }
            return generateRSAKeyPairWithOpFlags(token, rsaparams.getKeysize(), rsaparams.getPublicExponent().longValue(), temporaryPairMode, sensitivePairMode, extractablePairMode, (int) opFlags, (int) opFlagsMask);
        } else {
            return generateRSAKeyPairWithOpFlags(token, DEFAULT_RSA_KEY_SIZE, DEFAULT_RSA_PUBLIC_EXPONENT.longValue(), temporaryPairMode, sensitivePairMode, extractablePairMode, (int) opFlags, (int) opFlagsMask);
        }
    } else if (algorithm == KeyPairAlgorithm.DSA) {
        if (params == null) {
            params = PQG1024;
        }
        DSAParameterSpec dsaParams = (DSAParameterSpec) params;
        return generateDSAKeyPairWithOpFlags(token, PQGParams.BigIntegerToUnsignedByteArray(dsaParams.getP()), PQGParams.BigIntegerToUnsignedByteArray(dsaParams.getQ()), PQGParams.BigIntegerToUnsignedByteArray(dsaParams.getG()), temporaryPairMode, sensitivePairMode, extractablePairMode, (int) opFlags, (int) opFlagsMask);
    } else {
        assert (algorithm == KeyPairAlgorithm.EC);
        // requires JAVA 1.5 for ECParameters.
        // 
        // AlgorithmParameters ecParams =
        // AlgorithmParameters.getInstance("ECParameters");
        // ecParams.init(params);
        PK11ParameterSpec ecParams = (PK11ParameterSpec) params;
        return generateECKeyPairWithOpFlags(token, ecParams.getEncoded(), /* curve */
        temporaryPairMode, sensitivePairMode, extractablePairMode, (int) opFlags, (int) opFlagsMask);
    }
}
Also used : DSAParameterSpec(java.security.spec.DSAParameterSpec) TokenException(org.mozilla.jss.crypto.TokenException) RSAKeyGenParameterSpec(java.security.spec.RSAKeyGenParameterSpec)

Example 18 with TokenException

use of org.mozilla.jss.crypto.TokenException in project jss by dogtagpki.

the class PK11KeyWrapper method unwrapSymmetric.

private SymmetricKey unwrapSymmetric(byte[] wrapped, SymmetricKey.Type type, int usageEnum, int keyLen) throws TokenException, IllegalStateException, InvalidAlgorithmParameterException {
    if (state != UNWRAP) {
        throw new IllegalStateException();
    }
    if ((!algorithm.isPadded()) && (type == SymmetricKey.RC4)) {
        if (keyLen <= 0) {
            throw new InvalidAlgorithmParameterException("RC4 keys wrapped in unpadded algorithms need key length" + " specified when unwrapping");
        }
    } else {
    // Don't use the key length
    // keyLen = 0;
    }
    /* Since we DONT want permanent,make the temporary arg true */
    boolean temporary = true;
    if (algorithm == KeyWrapAlgorithm.PLAINTEXT) {
        return nativeUnwrapSymPlaintext(token, wrapped, algFromType(type), usageEnum, temporary);
    }
    if (symKey != null) {
        assert (pubKey == null && privKey == null);
        return nativeUnwrapSymWithSym(token, symKey, wrapped, algorithm, algFromType(type), keyLen, IV, usageEnum, temporary);
    }
    assert (privKey != null && pubKey == null && symKey == null);
    NativeProxy params = null;
    long params_size = 0;
    if (parameters != null) {
        try {
            ((NativeEnclosure) parameters).open();
            params = ((NativeEnclosure) parameters).mPointer;
            params_size = ((NativeEnclosure) parameters).mPointerSize;
        } catch (Exception e) {
            throw new TokenException(e.getMessage(), e);
        }
    }
    try {
        return nativeUnwrapSymWithPriv(token, privKey, wrapped, algorithm, algFromType(type), keyLen, params, params_size, usageEnum);
    } finally {
        if (parameters != null) {
            try {
                ((NativeEnclosure) parameters).close();
            } catch (Exception e) {
                throw new TokenException(e.getMessage(), e);
            }
        }
    }
}
Also used : NativeProxy(org.mozilla.jss.util.NativeProxy) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NativeEnclosure(org.mozilla.jss.util.NativeEnclosure) TokenException(org.mozilla.jss.crypto.TokenException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) TokenException(org.mozilla.jss.crypto.TokenException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 19 with TokenException

use of org.mozilla.jss.crypto.TokenException in project jss by dogtagpki.

the class TokenCallbackInfo method generateCertRequest.

/**
 * Generates a PKCS#10 certificate request including Begin/End brackets
 * @param subject subject dn of the certificate
 * @param keysize size of the key
 * @param keyType "rsa" or "dsa"
 * @param P The DSA prime parameter
 * @param Q The DSA sub-prime parameter
 * @param G The DSA base parameter
 * @return String that represents a PKCS#10 b64 encoded blob with
 * begin/end brackets
 */
@Override
public String generateCertRequest(String subject, int keysize, String keyType, byte[] P, byte[] Q, byte[] G) throws TokenException, InvalidParameterException, PQGParamGenException {
    if (keyType.equalsIgnoreCase("dsa")) {
        if ((P == null) && (Q == null) && (G == null)) {
            PQGParams pqg;
            try {
                pqg = PQGParams.generate(keysize);
            } catch (PQGParamGenException e) {
                throw e;
            }
            byte[] p = PQGParams.BigIntegerToUnsignedByteArray(pqg.getP());
            byte[] q = PQGParams.BigIntegerToUnsignedByteArray(pqg.getQ());
            byte[] g = PQGParams.BigIntegerToUnsignedByteArray(pqg.getG());
            P = p;
            Q = q;
            G = g;
            String pk10String;
            try {
                pk10String = generatePK10(subject, keysize, keyType, p, q, g);
            } catch (TokenException e) {
                throw e;
            } catch (InvalidParameterException e) {
                throw e;
            }
            return ("-----BEGIN NEW CERTIFICATE REQUEST-----\n" + pk10String + "\n-----END NEW CERTIFICATE REQUEST-----");
        } else if ((P == null) || (Q == null) || (G == null)) {
            throw new InvalidParameterException("need all P, Q, and G");
        }
    }
    String pk10String;
    try {
        pk10String = generatePK10(subject, keysize, keyType, P, Q, G);
    } catch (TokenException e) {
        throw e;
    } catch (InvalidParameterException e) {
        throw e;
    }
    return ("-----BEGIN NEW CERTIFICATE REQUEST-----\n" + pk10String + "\n-----END NEW CERTIFICATE REQUEST-----");
}
Also used : PQGParams(org.mozilla.jss.crypto.PQGParams) InvalidParameterException(java.security.InvalidParameterException) PQGParamGenException(org.mozilla.jss.crypto.PQGParamGenException) TokenException(org.mozilla.jss.crypto.TokenException)

Example 20 with TokenException

use of org.mozilla.jss.crypto.TokenException in project jss by dogtagpki.

the class SSLClientAuth method generateCerts.

private void generateCerts(CryptoManager cm, int serialNum) {
    // RSA Key with default exponent
    int keyLength = 4096;
    try {
        java.security.KeyPairGenerator kpg = java.security.KeyPairGenerator.getInstance("RSA", "Mozilla-JSS");
        kpg.initialize(keyLength);
        KeyPair caPair = kpg.genKeyPair();
        // Generate CA cert
        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), "SSLCA-" + serialNum);
        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", "localhost", 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);
    } catch (CertificateEncodingException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (NoSuchAlgorithmException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (NoSuchProviderException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (NicknameConflictException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (UserCertConflictException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (TokenException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (NoSuchItemOnTokenException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(1);
    }
}
Also used : UserCertConflictException(org.mozilla.jss.UserCertConflictException) KeyPair(java.security.KeyPair) NicknameConflictException(org.mozilla.jss.NicknameConflictException) NoSuchItemOnTokenException(org.mozilla.jss.crypto.NoSuchItemOnTokenException) CertificateEncodingException(java.security.cert.CertificateEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(org.mozilla.jss.crypto.X509Certificate) NicknameConflictException(org.mozilla.jss.NicknameConflictException) SocketException(java.net.SocketException) NoSuchItemOnTokenException(org.mozilla.jss.crypto.NoSuchItemOnTokenException) ObjectNotFoundException(org.mozilla.jss.crypto.ObjectNotFoundException) EOFException(java.io.EOFException) UserCertConflictException(org.mozilla.jss.UserCertConflictException) TokenException(org.mozilla.jss.crypto.TokenException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) CertificateEncodingException(java.security.cert.CertificateEncodingException) InternalCertificate(org.mozilla.jss.crypto.InternalCertificate) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) NoSuchItemOnTokenException(org.mozilla.jss.crypto.NoSuchItemOnTokenException) TokenException(org.mozilla.jss.crypto.TokenException) NoSuchProviderException(java.security.NoSuchProviderException) InternalCertificate(org.mozilla.jss.crypto.InternalCertificate) Certificate(org.mozilla.jss.pkix.cert.Certificate) X509Certificate(org.mozilla.jss.crypto.X509Certificate)

Aggregations

TokenException (org.mozilla.jss.crypto.TokenException)28 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)11 NoSuchItemOnTokenException (org.mozilla.jss.crypto.NoSuchItemOnTokenException)10 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)9 CryptoManager (org.mozilla.jss.CryptoManager)9 NotInitializedException (org.mozilla.jss.NotInitializedException)9 InvalidKeyException (java.security.InvalidKeyException)8 NoSuchTokenException (org.mozilla.jss.NoSuchTokenException)8 CryptoToken (org.mozilla.jss.crypto.CryptoToken)8 ObjectNotFoundException (org.mozilla.jss.crypto.ObjectNotFoundException)8 X509Certificate (org.mozilla.jss.crypto.X509Certificate)8 SymmetricKey (org.mozilla.jss.crypto.SymmetricKey)7 SecretKeyFacade (org.mozilla.jss.crypto.SecretKeyFacade)5 CharConversionException (java.io.CharConversionException)4 TokenRuntimeException (org.mozilla.jss.crypto.TokenRuntimeException)4 CertificateException (java.security.cert.CertificateException)3 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)3 PBEKeyGenParams (org.mozilla.jss.crypto.PBEKeyGenParams)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2