Example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption

List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption.

Prototype

ASN1ObjectIdentifier sha1WithRSAEncryption

To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption.

Click Source Link

Document

PKCS#1: 1.2.840.113549.1.1.5

Usage

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   ww  w  . ja v a2s.co 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.cesecore.certificates.util.AlgorithmTools.java

License:Open Source License

/** Calculates which signature algorithm to use given a key type and a digest algorithm
 * /*from w w w. j  a v a  2 s . c  om*/
 * @param digestAlg objectId of a digest algorithm, CMSSignedGenerator.DIGEST_SHA256 etc
 * @param keyAlg RSA, EC, DSA
 * @return ASN1ObjectIdentifier with the id of PKCSObjectIdentifiers.sha1WithRSAEncryption, X9ObjectIdentifiers.ecdsa_with_SHA1, X9ObjectIdentifiers.id_dsa_with_sha1, etc
 */
public static ASN1ObjectIdentifier getSignAlgOidFromDigestAndKey(final String digestAlg, final String keyAlg) {
    if (log.isTraceEnabled()) {
        log.trace(">getSignAlg(" + digestAlg + "," + keyAlg + ")");
    }
    // Default to SHA1WithRSA if everything else fails    
    ASN1ObjectIdentifier oid = PKCSObjectIdentifiers.sha1WithRSAEncryption;
    if (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_EC)
            || keyAlg.equals(AlgorithmConstants.KEYALGORITHM_ECDSA)) {
        oid = X9ObjectIdentifiers.ecdsa_with_SHA1;
    } else if (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_DSA)) {
        oid = X9ObjectIdentifiers.id_dsa_with_sha1;
    } else if (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) {
        oid = CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001;
    } else if (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) {
        oid = new ASN1ObjectIdentifier(CesecoreConfiguration.getOidDstu4145());
    }
    if (digestAlg != null) {
        if (digestAlg.equals(CMSSignedGenerator.DIGEST_SHA256)
                && keyAlg.equals(AlgorithmConstants.KEYALGORITHM_RSA)) {
            oid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
        } else if (digestAlg.equals(CMSSignedGenerator.DIGEST_SHA512)
                && keyAlg.equals(AlgorithmConstants.KEYALGORITHM_RSA)) {
            oid = PKCSObjectIdentifiers.sha512WithRSAEncryption;
        } else if (digestAlg.equals(CMSSignedGenerator.DIGEST_MD5)
                && keyAlg.equals(AlgorithmConstants.KEYALGORITHM_RSA)) {
            oid = PKCSObjectIdentifiers.md5WithRSAEncryption;
        } else if (digestAlg.equals(CMSSignedGenerator.DIGEST_SHA256)
                && (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_ECDSA)
                        || keyAlg.equals(AlgorithmConstants.KEYALGORITHM_EC))) {
            oid = X9ObjectIdentifiers.ecdsa_with_SHA256;
        } else if (digestAlg.equals(CMSSignedGenerator.DIGEST_SHA224)
                && (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_ECDSA)
                        || keyAlg.equals(AlgorithmConstants.KEYALGORITHM_EC))) {
            oid = X9ObjectIdentifiers.ecdsa_with_SHA224;
        } else if (digestAlg.equals(CMSSignedGenerator.DIGEST_SHA384)
                && (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_ECDSA)
                        || keyAlg.equals(AlgorithmConstants.KEYALGORITHM_EC))) {
            oid = X9ObjectIdentifiers.ecdsa_with_SHA384;
        } else if (digestAlg.equals(CMSSignedGenerator.DIGEST_SHA512)
                && (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_ECDSA)
                        || keyAlg.equals(AlgorithmConstants.KEYALGORITHM_EC))) {
            oid = X9ObjectIdentifiers.ecdsa_with_SHA512;
        } else if (digestAlg.equals(CMSSignedGenerator.DIGEST_SHA256)
                && keyAlg.equals(AlgorithmConstants.KEYALGORITHM_DSA)) {
            oid = NISTObjectIdentifiers.dsa_with_sha256;
        } else if (digestAlg.equals(CMSSignedGenerator.DIGEST_SHA512)
                && keyAlg.equals(AlgorithmConstants.KEYALGORITHM_DSA)) {
            oid = NISTObjectIdentifiers.dsa_with_sha512;
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("getSignAlgOidFromDigestAndKey: " + oid.getId());
    }
    return oid;
}

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

License:Open Source License

/**
 * Returns the name of the algorithm corresponding to the specified OID
 * @param sigAlgOid//from w  ww. j a  va2  s. com
 * @return The name of the algorithm corresponding sigAlgOid or null if the algorithm is not recognized.
 */
public static String getAlgorithmNameFromOID(ASN1ObjectIdentifier sigAlgOid) {

    if (sigAlgOid.equals(PKCSObjectIdentifiers.md5WithRSAEncryption)) {
        return AlgorithmConstants.SIGALG_MD5_WITH_RSA;
    }

    if (sigAlgOid.equals(PKCSObjectIdentifiers.sha1WithRSAEncryption)) {
        return AlgorithmConstants.SIGALG_SHA1_WITH_RSA;
    }

    if (sigAlgOid.equals(PKCSObjectIdentifiers.sha256WithRSAEncryption)) {
        return AlgorithmConstants.SIGALG_SHA256_WITH_RSA;
    }

    if (sigAlgOid.equals(PKCSObjectIdentifiers.sha384WithRSAEncryption)) {
        return AlgorithmConstants.SIGALG_SHA384_WITH_RSA;
    }

    if (sigAlgOid.equals(PKCSObjectIdentifiers.sha512WithRSAEncryption)) {
        return AlgorithmConstants.SIGALG_SHA512_WITH_RSA;
    }

    if (sigAlgOid.equals(X9ObjectIdentifiers.ecdsa_with_SHA1)) {
        return AlgorithmConstants.SIGALG_SHA1_WITH_ECDSA;
    }

    if (sigAlgOid.equals(X9ObjectIdentifiers.ecdsa_with_SHA224)) {
        return AlgorithmConstants.SIGALG_SHA224_WITH_ECDSA;
    }

    if (sigAlgOid.equals(X9ObjectIdentifiers.ecdsa_with_SHA256)) {
        return AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA;
    }

    if (sigAlgOid.equals(X9ObjectIdentifiers.ecdsa_with_SHA384)) {
        return AlgorithmConstants.SIGALG_SHA384_WITH_ECDSA;
    }

    if (sigAlgOid.equals(X9ObjectIdentifiers.ecdsa_with_SHA512)) {
        return AlgorithmConstants.SIGALG_SHA512_WITH_ECDSA;
    }
    // GOST3410
    if (isGost3410Enabled() && sigAlgOid.getId().equalsIgnoreCase(CesecoreConfiguration.getOidGost3410())) {
        return AlgorithmConstants.SIGALG_GOST3411_WITH_ECGOST3410;
    }
    // DSTU4145
    if (isDstu4145Enabled() && sigAlgOid.getId().startsWith(CesecoreConfiguration.getOidDstu4145() + ".")) {
        return AlgorithmConstants.SIGALG_GOST3411_WITH_DSTU4145;
    }

    return null;
}

From source file:org.clever.Common.XMPPCommunicator.ScepRequest.java

License:Open Source License

public CertificationRequest createCsr(X500Principal subject, PublicKey pubKey, PrivateKey priKey,
        char[] password) throws GeneralSecurityException, IOException {
    AlgorithmIdentifier sha1withRsa = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);

    ASN1Set cpSet = new DERSet(new DERPrintableString(new String(password)));
    Attribute challengePassword = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, cpSet);
    ASN1Set attrs = new DERSet(challengePassword);

    SubjectPublicKeyInfo pkInfo = new SubjectPublicKeyInfo(
            (ASN1Sequence) ASN1Object.fromByteArray(pubKey.getEncoded()));

    Properties ht = new Properties();
    ht.put(X509Principal.CN, this.hostname);
    ht.put(X509Principal.C, this.C);
    ht.put(X509Principal.O, this.O);
    ht.put(X509Principal.OU, this.OU);
    ht.put(X509Principal.EmailAddress, this.hostname + "@" + this.domain);
    X509Name nn = new X509Name(ht);

    X509Name name = new X509Name(subject.toString());

    CertificationRequestInfo requestInfo = new CertificationRequestInfo(nn, pkInfo, attrs);

    Signature signer = Signature.getInstance("SHA1withRSA");
    signer.initSign(priKey);/* w  ww . ja v  a2s  . c  o  m*/
    signer.update(requestInfo.getEncoded());
    byte[] signatureBytes = signer.sign();
    DERBitString signature = new DERBitString(signatureBytes);

    return new CertificationRequest(requestInfo, sha1withRsa, signature);
}

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

License:Open Source License

@Test
public void test03HMACCrmfReq() throws Exception {

    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_HMAC);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "foo123");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.cmpConfiguration.setResponseProtection(ALIAS, "signature");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

    final PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false,
            null, null, null, null, null, null);
    assertNotNull("Generating CrmfRequest failed.", msg);
    final PKIMessage req = protectPKIMessage(msg, false, "foo123", "mykeyid", 567);
    assertNotNull("Protecting PKIMessage with HMACPbe failed.", req);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);//w w  w. ja v a 2s  .c om
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
    checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, req.getHeader().getSenderNonce().getOctets(),
            req.getHeader().getTransactionID().getOctets(), true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    final CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    final Certificate cert1 = checkCmpCertRepMessage(USER_DN, this.cacert, resp,
            ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
    assertNotNull("Crmf request did not return a certificate", cert1);
}

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

License:Open Source License

@Test
public void test04HMACRevReq() throws Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_HMAC);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "foo123");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    final X500Name revUserDN = new X500Name("CN=cmprevuser1,C=SE");
    final String revUsername = "cmprevuser1";
    String fingerprint = null;/*w  ww . ja  va2 s .c  o m*/
    try {

        Collection<Certificate> certs = this.certificateStoreSession
                .findCertificatesBySubjectAndIssuer(revUserDN.toString(), issuerDN);
        log.debug("Found " + certs.size() + " certificates for userDN \"" + USER_DN + "\"");
        Certificate cert = null, tmp = null;
        Iterator<Certificate> itr = certs.iterator();
        while (itr.hasNext()) {
            tmp = itr.next();
            if (!this.certificateStoreSession.isRevoked(issuerDN, CertTools.getSerialNumber(tmp))) {
                cert = tmp;
                break;
            }
        }
        if (cert == null) {
            createUser(revUsername, revUserDN.toString(), "foo123", true, this.caid,
                    SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
            KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
            cert = this.signSession.createCertificate(ADMIN, revUsername, "foo123",
                    new PublicKeyWrapper(admkeys.getPublic()));
        }
        assertNotNull("No certificate to revoke.", cert);

        fingerprint = CertTools.getFingerprintAsString(cert); // to be able to remove

        PKIMessage msg = genRevReq(issuerDN, revUserDN, CertTools.getSerialNumber(cert), this.cacert,
                this.nonce, this.transid, false, null, null);
        assertNotNull("Generating RevocationRequest failed.", msg);
        PKIMessage req = protectPKIMessage(msg, false, "foo123", "mykeyid", 567);
        assertNotNull("Protecting PKIMessage with HMACPbe failed.", req);

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, revUserDN, this.cacert,
                req.getHeader().getSenderNonce().getOctets(), req.getHeader().getTransactionID().getOctets(),
                true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revStatus = checkRevokeStatus(issuerDN, CertTools.getSerialNumber(cert));
        Assert.assertNotEquals("Revocation request failed to revoke the certificate",
                RevokedCertInfo.NOT_REVOKED, revStatus);
    } finally {
        if (this.eeAccessSession.findUser(ADMIN, revUsername) != null) {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, revUsername, ReasonFlags.unused);
        }
        this.internalCertStoreSession.removeCertificate(fingerprint);
    }

}

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

License:Open Source License

@Test
public void test05EECrmfReq() throws NoSuchAlgorithmException, EjbcaException, IOException, Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    final X500Name testUserDN = new X500Name("CN=cmptestuser5,C=SE");
    final String testUsername = "cmptestuser5";
    String fingerprint = null;/*from w w w. j av  a2s.c o m*/
    String fingerprint2 = null;
    AuthenticationToken admToken = null;
    Certificate admCert = null;
    try {
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false,
                null, null, null, null, pAlg, new DEROctetString(this.nonce));
        assertNotNull("Generating CrmfRequest failed.", msg);

        KeyPair admkeys = KeyTools.genKeys("512", "RSA");
        admToken = createAdminToken(admkeys, testUsername, testUserDN.toString(), this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        admCert = getCertFromCredentials(admToken);
        fingerprint = CertTools.getFingerprintAsString(admCert);

        CMPCertificate[] extraCert = getCMPCert(admCert);
        msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull(msg);
        //******************************************''''''
        final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
                "BC");
        sig.initVerify(admCert.getPublicKey());
        sig.update(CmpMessageHelper.getProtectedBytes(msg));
        boolean verified = sig.verify(msg.getProtection().getBytes());
        assertTrue("Signing the message failed.", verified);
        //***************************************************

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(msg);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert,
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
        Certificate cert2 = checkCmpCertRepMessage(testUserDN, this.cacert, resp,
                ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
        assertNotNull("CrmfRequest did not return a certificate", cert2);
        fingerprint2 = CertTools.getFingerprintAsString(cert2);
    } finally {
        removeAuthenticationToken(admToken, admCert, testUsername); // also removes testUsername
        this.internalCertStoreSession.removeCertificate(fingerprint);
        this.internalCertStoreSession.removeCertificate(fingerprint2);
    }
}

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

License:Open Source License

@Test
public void test06EERevReq() throws NoSuchAlgorithmException, EjbcaException, IOException, Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    Collection<Certificate> certs = this.certificateStoreSession
            .findCertificatesBySubjectAndIssuer(USER_DN.toString(), issuerDN);
    log.debug("Found " + certs.size() + " certificates for userDN \"" + USER_DN + "\"");
    Certificate cert = null, tmp = null;
    Iterator<Certificate> itr = certs.iterator();
    while (itr.hasNext()) {
        tmp = itr.next();/*from   w  w w . j  a v  a  2s . c  o m*/
        if (!this.certificateStoreSession.isRevoked(issuerDN, CertTools.getSerialNumber(tmp))) {
            cert = tmp;
            break;
        }
    }
    if (cert == null) {
        createUser("cmprevuser1", "CN=cmprevuser1,C=SE", "foo123", true, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
        cert = this.signSession.createCertificate(ADMIN, "cmprevuser1", "foo123",
                new PublicKeyWrapper(admkeys.getPublic()));
    }
    assertNotNull("No certificate to revoke.", cert);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage msg = genRevReq(issuerDN, USER_DN, CertTools.getSerialNumber(cert), this.cacert, this.nonce,
            this.transid, false, pAlg, null);
    assertNotNull("Generating CrmfRequest failed.", msg);

    String adminName = "cmpTestAdmin";
    KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
    AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE",
            this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    Certificate admCert = getCertFromCredentials(adminToken);
    CMPCertificate[] extraCert = getCMPCert(admCert);
    msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(msg);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(msg);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
    checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(),
            msg.getHeader().getTransactionID().getOctets(), true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    int revStatus = checkRevokeStatus(issuerDN, CertTools.getSerialNumber(cert));
    assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED,
            revStatus);

    removeAuthenticationToken(adminToken, admCert, adminName);
}

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

License:Open Source License

@Test
public void test07EERevReqWithUnknownCA()
        throws NoSuchAlgorithmException, EjbcaException, IOException, Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    Collection<Certificate> certs = this.certificateStoreSession
            .findCertificatesBySubjectAndIssuer(USER_DN.toString(), issuerDN);
    log.debug("Found " + certs.size() + " certificates for userDN \"" + USER_DN + "\"");
    Certificate cert = null, tmp = null;
    Iterator<Certificate> itr = certs.iterator();
    while (itr.hasNext()) {
        tmp = itr.next();//from  www.  j av a 2s  .  co  m
        if (!this.certificateStoreSession.isRevoked(issuerDN, CertTools.getSerialNumber(tmp))) {
            cert = tmp;
            break;
        }
    }
    final String userName = "cmprevuser1";
    if (cert == null) {
        createUser(userName, "CN=" + userName + ",C=SE", "foo123", true, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
        cert = this.signSession.createCertificate(ADMIN, "cmprevuser1", "foo123",
                new PublicKeyWrapper(admkeys.getPublic()));
    }
    try {
        assertNotNull("No certificate to revoke.", cert);

        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genRevReq("CN=cmprevuser1,C=SE", USER_DN, CertTools.getSerialNumber(cert), cert,
                this.nonce, this.transid, false, pAlg, null);
        assertNotNull("Generating CrmfRequest failed.", msg);

        String adminName = "cmpTestAdmin";
        KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
        AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE",
                this.caid, SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        Certificate admCert = getCertFromCredentials(adminToken);
        CMPCertificate[] extraCert = getCMPCert(admCert);
        msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull(msg);

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(msg);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, "CN=cmprevuser1,C=SE", USER_DN, this.cacert,
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revStatus = checkRevokeStatus(issuerDN, CertTools.getSerialNumber(cert));
        assertEquals("Revocation request succeeded", RevokedCertInfo.NOT_REVOKED, revStatus);
        ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        try {
            PKIMessage respObject = PKIMessage.getInstance(asn1InputStream.readObject());
            assertNotNull(respObject);

            PKIBody body = respObject.getBody();
            assertEquals(23, body.getType());
            ErrorMsgContent err = (ErrorMsgContent) body.getContent();
            String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
            String expectedErrMsg = "CA with DN 'C=SE,CN=cmprevuser1' is unknown";
            assertEquals(expectedErrMsg, errMsg);
            removeAuthenticationToken(adminToken, admCert, adminName);
        } finally {
            asn1InputStream.close();
        }
    } finally {
        this.endEntityManagementSession.deleteUser(ADMIN, userName);
    }
}

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

License:Open Source License

@Test
public void test08EECrmfReqMultipleAuthModules()
        throws NoSuchAlgorithmException, EjbcaException, IOException, Exception {
    String modules = CmpConfiguration.AUTHMODULE_HMAC + ";" + CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE;
    String parameters = "foo123" + ";" + "TestCA";
    this.cmpConfiguration.setAuthenticationModule(ALIAS, modules);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, parameters);
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null,
            null, null, null, pAlg, null);
    assertNotNull("Generating CrmfRequest failed.", msg);

    String adminName = "cmpTestAdmin";
    KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
    AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE",
            this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    Certificate admCert = getCertFromCredentials(adminToken);
    CMPCertificate[] extraCert = getCMPCert(admCert);
    msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(msg);/*ww w  .j  av  a  2 s. c o m*/

    //********************************************
    final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
            "BC");
    sig.initVerify(admCert.getPublicKey());
    sig.update(CmpMessageHelper.getProtectedBytes(msg));
    boolean verified = sig.verify(msg.getProtection().getBytes());
    assertTrue("Signing the message failed.", verified);
    //********************************************

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(msg);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
    checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(),
            msg.getHeader().getTransactionID().getOctets(), true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
    Certificate cert2 = checkCmpCertRepMessage(USER_DN, this.cacert, resp,
            ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
    assertNotNull("CrmfRequest did not return a certificate", cert2);

    removeAuthenticationToken(adminToken, admCert, adminName);
}