Example usage for org.bouncycastle.cms CMSSignedGenerator DIGEST_SHA1

List of usage examples for org.bouncycastle.cms CMSSignedGenerator DIGEST_SHA1

Introduction

In this page you can find the example usage for org.bouncycastle.cms CMSSignedGenerator DIGEST_SHA1.

Prototype

String DIGEST_SHA1

To view the source code for org.bouncycastle.cms CMSSignedGenerator DIGEST_SHA1.

Click Source Link

Usage

From source file:de.mendelson.util.security.BCCryptoHelper.java

/**
 * Converts the passed algorithm or OID//  www .ja va 2s.c  om
 */
public String convertAlgorithmNameToOID(String algorithm) throws NoSuchAlgorithmException {
    if (algorithm == null) {
        throw new NoSuchAlgorithmException(
                "convertAlgorithmNameToOID: Unable to proceed - Algorithm is absent");
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_MD5)) {
        return (CMSSignedGenerator.DIGEST_MD5);
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_SHA1)) {
        return (CMSSignedGenerator.DIGEST_SHA1);
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_SHA224) || algorithm.equalsIgnoreCase("sha224")) {
        return (CMSSignedGenerator.DIGEST_SHA224);
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_SHA256) || algorithm.equalsIgnoreCase("sha256")) {
        return (CMSSignedGenerator.DIGEST_SHA256);
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_SHA384) || algorithm.equalsIgnoreCase("sha384")) {
        return (CMSSignedGenerator.DIGEST_SHA384);
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_SHA512) || algorithm.equalsIgnoreCase("sha512")) {
        return (CMSSignedGenerator.DIGEST_SHA512);
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_3DES)) {
        return ("1.2.840.113549.3.7");
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_DES)) {
        return ("1.3.14.3.2.7");
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_CAST5)) {
        return (CMSEnvelopedDataGenerator.CAST5_CBC);
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_IDEA)) {
        return (CMSEnvelopedDataGenerator.IDEA_CBC);
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_RC2)) {
        return (CMSEnvelopedDataGenerator.RC2_CBC);
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_RC4)) {
        return ("1.2.840.113549.3.4");
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_AES_128)) {
        return (CMSEnvelopedDataGenerator.AES128_CBC);
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_AES_192)) {
        return (CMSEnvelopedDataGenerator.AES192_CBC);
    } else if (algorithm.equalsIgnoreCase(ALGORITHM_AES_256)) {
        return (CMSEnvelopedDataGenerator.AES256_CBC);
    } else {
        throw new NoSuchAlgorithmException("Unsupported algorithm: " + algorithm);
    }
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

/**
 * Converts the passed algorithm or OID/*  w  ww  .  j a  v  a  2s. co m*/
 */
public String convertOIDToAlgorithmName(String oid) throws NoSuchAlgorithmException {
    if (oid == null) {
        throw new NoSuchAlgorithmException("convertOIDToAlgorithmName: OID is absent");
    } else if (oid.equalsIgnoreCase(CMSSignedGenerator.DIGEST_MD5)) {
        return (ALGORITHM_MD5);
    } else if (oid.equalsIgnoreCase(CMSSignedGenerator.DIGEST_SHA1)) {
        return (ALGORITHM_SHA1);
    } else if (oid.equalsIgnoreCase(CMSSignedGenerator.DIGEST_SHA224)) {
        return (ALGORITHM_SHA224);
    } else if (oid.equalsIgnoreCase(CMSSignedGenerator.DIGEST_SHA256)) {
        return (ALGORITHM_SHA256);
    } else if (oid.equalsIgnoreCase(CMSSignedGenerator.DIGEST_SHA384)) {
        return (ALGORITHM_SHA384);
    } else if (oid.equalsIgnoreCase(CMSSignedGenerator.DIGEST_SHA512)) {
        return (ALGORITHM_SHA512);
    } else if (oid.equalsIgnoreCase(CMSEnvelopedDataGenerator.CAST5_CBC)) {
        return (ALGORITHM_CAST5);
    } else if (oid.equalsIgnoreCase(CMSEnvelopedDataGenerator.DES_EDE3_CBC)) {
        return (ALGORITHM_3DES);
    } else if (oid.equalsIgnoreCase("1.3.14.3.2.7")) {
        return (ALGORITHM_DES);
    } else if (oid.equalsIgnoreCase(CMSEnvelopedDataGenerator.IDEA_CBC)) {
        return (ALGORITHM_IDEA);
    } else if (oid.equalsIgnoreCase(CMSEnvelopedDataGenerator.RC2_CBC)) {
        return (ALGORITHM_RC2);
    } else if (oid.equalsIgnoreCase("1.2.840.113549.3.4")) {
        return (ALGORITHM_RC4);
    } else if (oid.equalsIgnoreCase(CMSEnvelopedDataGenerator.AES128_CBC)) {
        return (ALGORITHM_AES_128);
    } else if (oid.equalsIgnoreCase(CMSEnvelopedDataGenerator.AES192_CBC)) {
        return (ALGORITHM_AES_192);
    } else if (oid.equalsIgnoreCase(CMSEnvelopedDataGenerator.AES256_CBC)) {
        return (ALGORITHM_AES_256);
    } else {
        throw new NoSuchAlgorithmException("Unsupported algorithm: OID " + oid);
    }
}

From source file:org.cesecore.certificates.ca.X509CA.java

License:Open Source License

@Override
public byte[] createPKCS7(CryptoToken cryptoToken, Certificate cert, boolean includeChain)
        throws SignRequestSignatureException {
    // First verify that we signed this certificate
    try {/*from  www . ja  v a2  s . co  m*/
        if (cert != null) {
            final PublicKey verifyKey;
            final X509Certificate cacert = (X509Certificate) getCACertificate();
            if (cacert != null) {
                verifyKey = cacert.getPublicKey();
            } else {

                verifyKey = cryptoToken
                        .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));

            }
            cert.verify(verifyKey);
        }
    } catch (CryptoTokenOfflineException e) {
        throw new SignRequestSignatureException("The cryptotoken was not available, could not create a PKCS7",
                e);
    } catch (InvalidKeyException e) {
        throw new SignRequestSignatureException("The specified certificate contains the wrong public key.", e);
    } catch (CertificateException e) {
        throw new SignRequestSignatureException("An encoding error was encountered.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignRequestSignatureException(
                "The certificate provided was signed with an invalid algorithm.", e);
    } catch (NoSuchProviderException e) {
        throw new SignRequestSignatureException(
                "The crypto provider was not found for verification of the certificate.", e);
    } catch (SignatureException e) {
        throw new SignRequestSignatureException("Cannot verify certificate in createPKCS7(), did I sign this?",
                e);
    }

    Collection<Certificate> chain = getCertificateChain();
    ArrayList<X509CertificateHolder> certList = new ArrayList<X509CertificateHolder>();
    try {
        if (cert != null) {
            certList.add(new JcaX509CertificateHolder((X509Certificate) cert));
        }
        if (includeChain) {
            for (Certificate certificate : chain) {
                certList.add(new JcaX509CertificateHolder((X509Certificate) certificate));
            }
        }
    } catch (CertificateEncodingException e) {
        throw new SignRequestSignatureException("Could not encode certificate", e);
    }
    try {
        CMSTypedData msg = new CMSProcessableByteArray("EJBCA".getBytes());
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        final PrivateKey privateKey = cryptoToken
                .getPrivateKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));
        if (privateKey == null) {
            String msg1 = "createPKCS7: Private key does not exist!";
            log.debug(msg1);
            throw new SignRequestSignatureException(msg1);
        }
        String signatureAlgorithmName = AlgorithmTools
                .getAlgorithmNameFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privateKey.getAlgorithm());
        try {
            ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName)
                    .setProvider(cryptoToken.getSignProviderName()).build(privateKey);
            JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
                    calculatorProviderBuilder.build());
            gen.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) getCACertificate()));
        } catch (OperatorCreationException e) {
            throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e);
        }
        gen.addCertificates(new CollectionStore(certList));
        CMSSignedData s = null;
        CAToken catoken = getCAToken();
        if (catoken != null && !(cryptoToken instanceof NullCryptoToken)) {
            log.debug("createPKCS7: Provider=" + cryptoToken.getSignProviderName() + " using algorithm "
                    + privateKey.getAlgorithm());
            s = gen.generate(msg, true);
        } else {
            String msg1 = "CA Token does not exist!";
            log.debug(msg);
            throw new SignRequestSignatureException(msg1);
        }
        return s.getEncoded();
    } catch (CryptoTokenOfflineException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        //FIXME: This right here is just nasty
        throw new RuntimeException(e);
    }
}

From source file:org.cesecore.certificates.util.AlgorithmTools.java

License:Open Source License

/** 
 * Get the digest algorithm corresponding to the signature algorithm. This is used for the creation of
 * PKCS7 file. SHA1 shall always be used, but it is not working with GOST which needs GOST3411 digest.
 * /*from   w w  w.  j a v a2 s  . c  o m*/
 */
public static String getDigestFromSigAlg(String sigAlg) {
    if (sigAlg.toUpperCase().contains("GOST") || sigAlg.toUpperCase().contains("DSTU")) {
        return CMSSignedGenerator.DIGEST_GOST3411;
    } else {
        if (sigAlg.equals(X9ObjectIdentifiers.ecdsa_with_SHA1.getId())
                || sigAlg.equals(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId())) {
            return CMSSignedGenerator.DIGEST_SHA1;
        } else if (sigAlg.equals(X9ObjectIdentifiers.ecdsa_with_SHA224.getId())
                || sigAlg.equals(PKCSObjectIdentifiers.sha224WithRSAEncryption.getId())) {
            return CMSSignedGenerator.DIGEST_SHA224;
        } else if (sigAlg.equals(X9ObjectIdentifiers.ecdsa_with_SHA256.getId())
                || sigAlg.equals(PKCSObjectIdentifiers.sha256WithRSAEncryption.getId())) {
            return CMSSignedGenerator.DIGEST_SHA256;
        } else if (sigAlg.equals(X9ObjectIdentifiers.ecdsa_with_SHA384.getId())
                || sigAlg.equals(PKCSObjectIdentifiers.sha384WithRSAEncryption.getId())) {
            return CMSSignedGenerator.DIGEST_SHA384;
        } else if (sigAlg.equals(X9ObjectIdentifiers.ecdsa_with_SHA512.getId())
                || sigAlg.equals(PKCSObjectIdentifiers.sha512WithRSAEncryption.getId())) {
            return CMSSignedGenerator.DIGEST_SHA512;
        } else if (sigAlg.equals(PKCSObjectIdentifiers.md5WithRSAEncryption.getId())) {
            return CMSSignedGenerator.DIGEST_MD5;
        } else if (sigAlg.equals(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001.getId())) {
            return CMSSignedGenerator.DIGEST_GOST3411;
        }
    }
    return CMSSignedGenerator.DIGEST_SHA1;

}

From source file:org.ejbca.core.model.ca.caadmin.CmsCAServiceTest.java

License:Open Source License

@Test
public void testCmsCAServiceActive() throws Exception {

    // Activate the service first
    testActivateCmsCAService();/*from   w  w w.ja  v  a  2 s .  c  o m*/

    CmsCAServiceRequest request = new CmsCAServiceRequest(doc, CmsCAServiceRequest.MODE_SIGN);
    CmsCAServiceResponse resp = null;
    // Try the request again
    boolean active = true;
    try {
        resp = (CmsCAServiceResponse) caAdminSession.extendedService(admin, getTestCAId(), request);
    } catch (ExtendedCAServiceNotActiveException e) {
        active = false;
    }
    // By default the CA service is not active
    assertTrue(active);

    assertNotNull(resp);
    byte[] respdoc = resp.getCmsDocument();
    assertNotNull(resp);
    CMSSignedData csd = new CMSSignedData(respdoc);
    SignerInformationStore infoStore = csd.getSignerInfos();
    @SuppressWarnings("unchecked")
    Collection<SignerInformation> signers = infoStore.getSigners();
    Iterator<SignerInformation> iter = signers.iterator();
    if (iter.hasNext()) {
        SignerInformation si = iter.next();
        assertNotNull(si);
        // log.info("Digest alg is: "+si.getDigestAlgOID());
        assertEquals(CMSSignedGenerator.DIGEST_SHA1, si.getDigestAlgOID());
        SignerId sid = si.getSID();
        // log.info(sid.toString());
        X500Name issuer = sid.getIssuer();
        assertNotNull(issuer);
        assertEquals("CN=TEST", issuer.toString());
    }
    Store store = csd.getCertificates();
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> certs = store.getMatches(null);
    assertEquals(2, certs.size());

    CMSProcessable cp = csd.getSignedContent();
    Object o = cp.getContent();
    byte[] ob = (byte[]) o;
    assertEquals(new String(doc), new String(ob));
}

From source file:org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAService.java

License:Open Source License

@Override
public ExtendedCAServiceResponse extendedService(final CryptoToken cryptoToken,
        final ExtendedCAServiceRequest request) throws ExtendedCAServiceRequestException,
        IllegalExtendedCAServiceRequestException, ExtendedCAServiceNotActiveException {
    if (log.isTraceEnabled()) {
        log.trace(">extendedService");
    }//from  w w w .ja  v a2s  .c om
    if (!(request instanceof CmsCAServiceRequest)) {
        throw new IllegalExtendedCAServiceRequestException();
    }
    if (getStatus() != ExtendedCAServiceInfo.STATUS_ACTIVE) {
        final String msg = intres.getLocalizedMessage("caservice.notactive", "CMS");
        log.error(msg);
        throw new ExtendedCAServiceNotActiveException(msg);
    }
    ExtendedCAServiceResponse returnval = null;
    final X509Certificate signerCert = (X509Certificate) certificatechain.get(0);
    final CmsCAServiceRequest serviceReq = (CmsCAServiceRequest) request;
    // Create the signed data
    final CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator();
    try {
        byte[] resp = serviceReq.getDoc();
        // Add our signer info and sign the message
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_SIGN) != 0) {
            final List<X509Certificate> x509CertChain = new ArrayList<X509Certificate>();
            for (Certificate certificate : certificatechain) {
                x509CertChain.add((X509Certificate) certificate);
            }
            gen1.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(x509CertChain)));
            JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
                    calculatorProviderBuilder.build());
            ASN1ObjectIdentifier oid = AlgorithmTools
                    .getSignAlgOidFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privKey.getAlgorithm());
            String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid);
            JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithmName)
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            ContentSigner contentSigner = signerBuilder.build(privKey);
            gen1.addSignerInfoGenerator(builder.build(contentSigner, signerCert));
            final CMSTypedData msg = new CMSProcessableByteArray(resp);
            final CMSSignedData s = gen1.generate(msg, true);
            resp = s.getEncoded();
        }
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_ENCRYPT) != 0) {
            CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
            edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(getCMSCertificate())
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME));
            JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(
                    PKCSObjectIdentifiers.des_EDE3_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME);
            CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(resp),
                    jceCMSContentEncryptorBuilder.build());
            resp = ed.getEncoded();
        }
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_DECRYPT) != 0) {
            final CMSEnvelopedData ed = new CMSEnvelopedData(resp);
            final RecipientInformationStore recipients = ed.getRecipientInfos();
            final X500Name issuer = X500Name
                    .getInstance(getCMSCertificate().getIssuerX500Principal().getEncoded());
            final KeyTransRecipientId id = new KeyTransRecipientId(issuer,
                    getCMSCertificate().getSerialNumber());
            final RecipientInformation recipient = recipients.get(id);
            if (recipient != null) {
                JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(this.privKey);
                // Provider for decrypting the symmetric key 
                rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME);
                rec.setProvider(cryptoToken.getSignProviderName());
                // We can use a different provider for decrypting the content, for example of we used a PKCS#11 provider above we could use the BC provider below
                resp = recipient.getContent(rec);
            }
        }
        returnval = new CmsCAServiceResponse(resp);
    } catch (CMSException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (IOException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (OperatorCreationException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (CertificateEncodingException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<extendedService");
    }
    return returnval;
}

From source file:org.ejbca.core.model.ca.caadmin.X509CA.java

License:Open Source License

public byte[] createPKCS7(Certificate cert, boolean includeChain) throws SignRequestSignatureException {
    // Verify using the CA certificate before returning
    // If we can not verify the issued certificate using the CA certificate we don't want to issue this certificate
    // because something is wrong...
    try {/*  w  w w.  ja  va2s. c  om*/
        if (cert != null) {
            PublicKey verifyKey;
            X509Certificate cacert = (X509Certificate) getCACertificate();
            if (cacert != null) {
                verifyKey = cacert.getPublicKey();
            } else {
                verifyKey = getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN);
            }
            cert.verify(verifyKey);
        }
    } catch (Exception e) {
        throw new SignRequestSignatureException("Cannot verify certificate in createPKCS7(), did I sign this?");
    }
    Collection<Certificate> chain = getCertificateChain();
    ArrayList<Certificate> certList = new ArrayList<Certificate>();
    if (cert != null) {
        certList.add(cert);
    }
    if (includeChain) {
        certList.addAll(chain);
    }
    try {
        CMSProcessable msg = new CMSProcessableByteArray("EJBCA".getBytes());
        CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                "BC");
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        if (getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN) == null) {
            String msg1 = "createPKCS7: Private key does not exist!";
            log.debug(msg1);
            throw new SignRequestSignatureException(msg1);
        }
        gen.addSigner(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN),
                (X509Certificate) getCACertificate(), CMSSignedGenerator.DIGEST_SHA1);
        gen.addCertificatesAndCRLs(certs);
        CMSSignedData s = null;
        CATokenContainer catoken = getCAToken();
        CATokenInfo tokeninfo = getCAInfo().getCATokenInfo();
        if (catoken != null && !(tokeninfo instanceof NullCATokenInfo)) {
            log.debug("createPKCS7: Provider=" + catoken.getProvider() + " using algorithm "
                    + getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN).getAlgorithm());
            s = gen.generate(msg, true, catoken.getProvider());
        } else {
            String msg1 = "CA Token does not exist!";
            log.debug(msg);
            throw new SignRequestSignatureException(msg1);
        }
        return s.getEncoded();
    } catch (CATokenOfflineException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java

License:Open Source License

/**
 * Tests the possibility to use different signature algorithms in CMP requests and responses.
 * /*from   w w w . j av a  2 s.c o  m*/
 * A CRMF request, signed using ECDSA with SHA1, is sent to a CA that uses RSA with SHA256 as signature algorithm.
 * The expected response is signed by RSA with SHA1.
 * 
 * @throws Exception
 */
@Test
public void test23EECAuthWithRSAandECDSA() throws Exception {
    log.trace(">test23EECAuthWithRSAandECDSA()");

    //-------------- Set the necessary configurations

    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.cmpConfiguration.setRANameGenScheme(ALIAS, "DN");
    this.cmpConfiguration.setRANameGenParams(ALIAS, "CN");
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //---------------- Send a CMP initialization request
    AuthenticationToken admToken = null;
    final String testAdminDN = "CN=cmptestadmin,C=SE";
    final String testAdminName = "cmptestadmin";
    X509Certificate admCert = null;
    String fp = null, fp2 = null;
    try {
        KeyPair keys = KeyTools.genKeys("prime192v1", AlgorithmConstants.KEYALGORITHM_ECDSA);

        final X500Name userDN = new X500Name("CN=cmpmixuser");
        final byte[] _nonce = CmpMessageHelper.createSenderNonce();
        final byte[] _transid = CmpMessageHelper.createSenderNonce();
        final AlgorithmIdentifier pAlg = new AlgorithmIdentifier(X9ObjectIdentifiers.ecdsa_with_SHA1);
        PKIMessage req = genCertReq(issuerDN, userDN, keys, this.cacert, _nonce, _transid, false, null, null,
                null, null, pAlg, null);

        createUser(testAdminName, testAdminDN, "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        KeyPair admkeys = KeyTools.genKeys("prime192v1", AlgorithmConstants.KEYALGORITHM_ECDSA);
        admToken = createAdminToken(admkeys, testAdminName, testAdminDN, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        admCert = getCertFromCredentials(admToken);
        fp = CertTools.getFingerprintAsString(admCert);

        CMPCertificate[] extraCert = getCMPCert(admCert);
        req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(),
                CMSSignedGenerator.DIGEST_SHA1, "BC");
        assertNotNull(req);

        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        byte[] ba = bao.toByteArray();
        // Send request and receive response
        byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, userDN, this.cacert, _nonce, _transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
        fp2 = CertTools.getFingerprintAsString(cert);

    } finally {
        removeAuthenticationToken(admToken, admCert, testAdminName);
        this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, "cmpmixuser", ReasonFlags.unused);
        this.internalCertStoreSession.removeCertificate(fp);
        this.internalCertStoreSession.removeCertificate(fp2);
    }
    log.trace("<test23EECAuthWithRSAandECDSA()");
}

From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java

License:Open Source License

@Test
public void testNovosecClientRequestSHA1() throws IOException, InvalidKeyException, NoSuchAlgorithmException,
        NoSuchProviderException, InvalidAlgorithmParameterException, SignatureException, IllegalStateException,
        OperatorCreationException, CertificateException {
    doNovosecClientRequest("SHA1WithRSA", CMSSignedGenerator.DIGEST_SHA1,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
}

From source file:org.ejbca.core.protocol.cmp.CrmfRequestTest.java

License:Open Source License

@Test
public void test02CrmfHttpUnknowUserSignedMessage() throws Exception {
    // A name that does not exist
    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage req = genCertReq(ISSUER_DN, USER_DN, this.keys, this.cacert, nonce, transid, false, null, null,
            null, null, null, null);/*from ww w .  j  a  va  2 s .  com*/
    assertNotNull(req);
    X509Certificate signCert = CertTools.genSelfCert("CN=CMP Sign Test", 3650, null, this.keys.getPrivate(),
            this.keys.getPublic(), "SHA256WithRSA", false);
    ArrayList<Certificate> signCertColl = new ArrayList<Certificate>();
    signCertColl.add(signCert);
    CmpMessageHelper.signPKIMessage(req, signCertColl, this.keys.getPrivate(), CMSSignedGenerator.DIGEST_SHA1,
            "BC");
    // PKIMessage req = protectPKIMessage(req1, false, "foo123", "mykeyid", 567);
    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
    checkCmpResponseGeneral(resp, ISSUER_DN, USER_DN, this.cacert, nonce, transid, true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpFailMessage(resp, "Wrong username or password", 1, reqId, 7, PKIFailureInfo.incorrectData); // Expects a CertificateResponse (reject) message with error
    // FailInfo.INCORRECT_DATA
}