Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

List of usage examples for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream.

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

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

License:Open Source License

/**
 * Sends a KeyUpdateRequest in RA mode when the authentication module is NOT set to 'EndEntityCertificate'. 
 * A CMP error message is expected and no certificate renewal.
 * //from  w  ww .  jav a 2  s. c om
 * - Pre-configuration: Sets the operational mode to RA mode (cmp.raoperationalmode=ra)
 * - Pre-configuration: Sets the cmp.authenticationmodule to 'DnPartPwd'
 * - Pre-configuration: Sets the cmp.authenticationparameters to 'OU'
 * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful.
 * - Generates a CMP KeyUpdate Request and tests that such request has been created.
 * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null
 * - Verifies the signature of the CMP request
 * - Sends the request using HTTP and receives an response.
 * - Examines the response:
 *      - Checks that the response is not empty or null
 *      - Checks that the protection algorithm is sha1WithRSAEncryption
 *      - Check that the signer is the expected CA
 *      - Verifies the response signature
 *      - Checks that the response's senderNonce is 16 bytes long
 *      - Checks that the request's senderNonce is the same as the response's recipientNonce
 *      - Checks that the request and the response has the same transactionID
 *      - Obtains the certificate from the response
 *      - Checks that the obtained certificate has the right subjectDN and issuerDN
 * 
 * @throws Exception
 */
@Test
public void test12ECCNotSetInRA() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace("test12ECCNotSetInRA()");
    }

    this.cmpConfiguration.setRAMode(this.cmpAlias, true);
    this.cmpConfiguration.setAuthenticationModule(this.cmpAlias, CmpConfiguration.AUTHMODULE_DN_PART_PWD);
    this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "OU");
    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, true);
    this.cmpConfiguration.setCMPDefaultCA(this.cmpAlias, "");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //------------------ create the user and issue his first certificate -------------
    createUser(this.username, this.userDN.toString(), "foo123");
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final Certificate certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123",
            new PublicKeyWrapper(keys.getPublic()));
    assertNotNull("Failed to create a test certificate", certificate);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, this.userDN,
            null, pAlg, null);
    assertNotNull("Failed to generate a CMP renewal request", req);

    createUser("cmpTestAdmin", "CN=cmpTestAdmin,C=SE", "foo123");
    KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
    AuthenticationToken admToken = createAdminToken(admkeys, "cmpTestAdmin", "CN=cmpTestAdmin,C=SE");
    final Certificate admCert = getCertFromCredentials(admToken);
    CMPCertificate[] extraCert = getCMPCert(admCert);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    //send request and recieve response
    byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    final PKIBody body = respObject.getBody();
    assertEquals(23, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    final String expectedErrMsg = "EndEnityCertificate authentication module is not configured. For a KeyUpdate request to be authentication "
            + "in RA mode, EndEntityCertificate authentication module has to be set and configured";
    assertEquals(expectedErrMsg, errMsg);

    removeAuthenticationToken(admToken, admCert, "cmpTestAdmin");

    if (log.isTraceEnabled()) {
        log.trace("<test12ECCNotSetInRA()");
    }

}

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

License:Open Source License

/**
 * Sends a KeyUpdateRequest by an admin concerning a certificate of another EndEntity in client mode. 
 * If the CA enforces unique public key, a CMP error message is expected and no certificate renewal.
 * If the CA does not enforce unique public key, a certificate will be renewed, though not the expected EndEntity certificate, but the admin certificate is renewed.
 * //w  w  w . j a v  a  2  s .co  m
 * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal)
 * - Pre-configuration: Sets the cmp.authenticationmodule to 'EndEntityCertificate'
 * - Pre-configuration: Sets the cmp.authenticationparameters to 'TestCA'
 * - Pre-configuration: Sets the cmp.allowautomatickeyupdate to 'true'
 * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful.
 * - Generates a CMP KeyUpdate Request and tests that such request has been created.
 * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null
 * - Verifies the signature of the CMP request
 * - Sends the request using HTTP and receives an response.
 * - Examines the response:
 *      - Checks that the response is not empty or null
 *      - Checks that the protection algorithm is sha1WithRSAEncryption
 *      - Check that the signer is the expected CA
 *      - Verifies the response signature
 *      - Checks that the response's senderNonce is 16 bytes long
 *      - Checks that the request's senderNonce is the same as the response's recipientNonce
 *      - Checks that the request and the response has the same transactionID
 *      - Obtains the certificate from the response
 *      - Checks that the obtained certificate has the right subjectDN and issuerDN
 * 
 * @throws Exception
 */
@Test
public void test13AdminInClientMode() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace("test09RAMode()");
    }

    this.cmpConfiguration.setRAMode(this.cmpAlias, false);
    this.cmpConfiguration.setAuthenticationModule(this.cmpAlias,
            CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "TestCA");
    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //------------------ create the user and issue his first certificate -------------
    createUser(this.username, this.userDN.toString(), "foo123");
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final Certificate certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123",
            new PublicKeyWrapper(keys.getPublic()));
    assertNotNull("Failed to create a test certificate", certificate);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, this.userDN,
            this.issuerDN, pAlg, new DEROctetString("CMPTESTPROFILE".getBytes()));
    assertNotNull("Failed to generate a CMP renewal request", req);
    //int reqId = req.getBody().getKur().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue();

    createUser("cmpTestAdmin", "CN=cmpTestAdmin,C=SE", "foo123");
    KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
    AuthenticationToken admToken = createAdminToken(admkeys, "cmpTestAdmin", "CN=cmpTestAdmin,C=SE");
    Certificate admCert = getCertFromCredentials(admToken);
    CMPCertificate[] extraCert = getCMPCert(admCert);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    //send request and recieve response
    byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    CAInfo cainfo = this.caSession.getCAInfo(ADMIN, this.caid);
    if (cainfo.isDoEnforceUniquePublicKeys()) {
        final PKIBody body = respObject.getBody();
        assertEquals(23, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        final String expectedErrMsg = "User 'cmpTestAdmin' is not allowed to use same key as another user is using.";
        assertEquals(expectedErrMsg, errMsg);
    } else {
        PKIBody body = respObject.getBody();
        int tag = body.getType();
        assertEquals(8, tag);
        CertRepMessage c = (CertRepMessage) body.getContent();
        assertNotNull(c);
        CMPCertificate cmpcert = c.getResponse()[0].getCertifiedKeyPair().getCertOrEncCert().getCertificate();
        assertNotNull(cmpcert);
        X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(cmpcert.getEncoded());
        assertNotNull("Failed to renew the certificate", cert);
        assertEquals("CN=cmpTestAdmin, C=SE", cert.getSubjectX500Principal().toString());
    }

    removeAuthenticationToken(admToken, admCert, "cmpTestAdmin");

    if (log.isTraceEnabled()) {
        log.trace("<test09RAMode()");
    }
}

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

License:Open Source License

/**
 * Sends a KeyUpdateRequest by an EndEntity concerning its own certificate in RA mode. 
 * A CMP error message is expected and no certificate renewal.
 * //from w  w w .  j a va 2  s  . c o m
 * @throws Exception
 */
@Test
public void test14EndEntityRequestingInRAMode() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">test14KeyUpdateRequestOK");
    }

    this.cmpConfiguration.setRAMode(this.cmpAlias, true);
    this.cmpConfiguration.setAuthenticationModule(this.cmpAlias,
            CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "TestCA");
    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //--------------- create the user and issue his first certificate -----------------
    createUser(this.username, this.userDN.toString(), "foo123");
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final Certificate certificate;
    try {
        certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123",
                new PublicKeyWrapper(keys.getPublic()));
    } catch (ObjectNotFoundException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (CADoesntExistsException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (EjbcaException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (AuthorizationDeniedException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (CesecoreException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    }
    assertNotNull("Failed to create a test certificate", certificate);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, null, null,
            pAlg, new DEROctetString(this.nonce));
    assertNotNull("Failed to generate a CMP renewal request", req);
    //int reqId = req.getBody().getKur().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue();

    CMPCertificate[] extraCert = getCMPCert(certificate);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    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, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    final PKIBody body = respObject.getBody();
    assertEquals(23, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();

    final String expectedErrMsg = "'CN=certRenewalUser,O=PrimeKey Solutions AB,C=SE' is not an authorized administrator.";
    assertEquals(expectedErrMsg, errMsg);

    if (log.isTraceEnabled()) {
        log.trace("<test14KeyUpdateRequestOK");
    }
}

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

License:Open Source License

private static X509Certificate checkKurCertRepMessage(X500Name eeDN, Certificate issuerCert, byte[] retMsg,
        int requestId) throws Exception {
    ///*from   w  w w  . j av a2s  .  c o m*/
    // Parse response message
    //

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }

    assertNotNull(respObject);

    // Verify body type
    PKIBody body = respObject.getBody();
    int tag = body.getType();
    assertEquals(8, tag);

    // Verify the response
    CertRepMessage c = (CertRepMessage) body.getContent();
    assertNotNull(c);
    CertResponse resp = c.getResponse()[0];
    assertNotNull(resp);
    assertEquals(resp.getCertReqId().getValue().intValue(), requestId);

    // Verify response status
    PKIStatusInfo info = resp.getStatus();
    assertNotNull(info);
    assertEquals(0, info.getStatus().intValue());

    // Verify response certificate
    CertifiedKeyPair kp = resp.getCertifiedKeyPair();
    assertNotNull(kp);
    CertOrEncCert cc = kp.getCertOrEncCert();
    assertNotNull(cc);
    final CMPCertificate cmpcert = cc.getCertificate();
    assertNotNull(cmpcert);
    X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(cmpcert.getEncoded());
    final X500Name name = new X500Name(CertTools.getSubjectDN(cert));
    assertArrayEquals(eeDN.getEncoded(), name.getEncoded());
    assertEquals(CertTools.stringToBCDNString(CertTools.getIssuerDN(cert)), CertTools.getSubjectDN(issuerCert));

    // Verify the issuer of cert
    CMPCertificate respCmpCaCert = c.getCaPubs()[0];
    final X509Certificate respCaCert = (X509Certificate) CertTools
            .getCertfromByteArray(respCmpCaCert.getEncoded());
    assertEquals(CertTools.getFingerprintAsString(issuerCert), CertTools.getFingerprintAsString(respCaCert));

    Collection<Certificate> cacerts = new ArrayList<Certificate>();
    cacerts.add(issuerCert);
    assertTrue(CertTools.verify(cert, cacerts));
    cacerts = new ArrayList<Certificate>();
    cacerts.add(respCaCert);
    assertTrue(CertTools.verify(cert, cacerts));
    return cert;
}

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

License:Open Source License

@Test
public void test03BlueXCrmf() throws Exception {
    PKIMessage req = null;/* w w w.  j a  va  2s  . c  om*/
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(bluexir));
    try {
        req = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    byte[] resp = sendCmpTcp(bluexir, 5);
    assertNotNull(resp);
    byte[] senderNonce = req.getHeader().getSenderNonce().getOctets();
    byte[] transId = req.getHeader().getTransactionID().getOctets();
    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    checkCmpResponseGeneral(resp, issuerDN, userDN, this.cacert, senderNonce, transId, true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
}

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

License:Open Source License

public PKIMessage getPKIMessage() {
    if (getMessage() == null) {
        try {//w  w  w.ja v a2  s .  c o m
            setMessage(PKIMessage
                    .getInstance(new ASN1InputStream(new ByteArrayInputStream(pkimsgbytes)).readObject()));
        } catch (IOException e) {
            log.error("Error decoding bytes for PKIMessage: ", e);
        }
    }
    return getMessage();
}

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

License:Open Source License

private PKIMessage createPKIMessage(final String issuerDN, final String subjectDN)
        throws InvalidAlgorithmParameterException, IOException {
    KeyPair keys = KeyTools.genKeys("1024", "RSA");
    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    myCertTemplate.setIssuer(new X500Name(issuerDN));
    myCertTemplate.setSubject(new X500Name(subjectDN));
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {//from   www  .  j av a  2s. com
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    int bcku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment | X509KeyUsage.nonRepudiation;
    X509KeyUsage ku = new X509KeyUsage(bcku);
    bOut = new ByteArrayOutputStream();
    dOut = new DEROutputStream(bOut);
    dOut.writeObject(ku);
    byte[] value = bOut.toByteArray();
    extgen.addExtension(Extension.keyUsage, false, new DEROctetString(value));
    myCertTemplate.setExtensions(extgen.generate());

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    ProofOfPossession myProofOfPossession = new ProofOfPossession();
    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String("foo123"));
    AttributeTypeAndValue[] avs = { av };
    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);
    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(new X500Name("CN=bogusSubject")),
            new GeneralName(new X500Name("CN=bogusIssuer")));
    myPKIHeader.setMessageTime(new DERGeneralizedTime(new Date()));
    myPKIHeader.setSenderNonce(new DEROctetString(CmpMessageHelper.createSenderNonce()));
    myPKIHeader.setTransactionID(new DEROctetString(CmpMessageHelper.createSenderNonce()));

    PKIBody myPKIBody = new PKIBody(0, myCertReqMessages);
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}

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

License:Open Source License

@Test
public void testNovosecRARequest() throws IOException, InvalidKeyException, NoSuchAlgorithmException,
        NoSuchProviderException, InvalidAlgorithmParameterException, CertificateEncodingException,
        SignatureException, IllegalStateException {
    // Check that we can parse a request from  Novosec (patched by EJBCA).
    // Read an initialization request with RAVerifiedPOP and PBE protection to see that we can process it
    ASN1InputStream in = new ASN1InputStream(novosecrapopir);
    try {/* ww  w. jav a2  s .  co m*/
        ASN1Primitive derObject = in.readObject();
        PKIMessage req = PKIMessage.getInstance(derObject);
        //log.info(req.toString());
        // Verify should be false if we do not allow RA verify POP here, since we don't have any normal POP
        CrmfRequestMessage msg = new CrmfRequestMessage(req, "CN=AdminCA1", false, "CN");
        assertFalse(msg.verify());
        // Verify should be ok when we allow RA verified POP
        msg = new CrmfRequestMessage(req, "CN=AdminCA1", true, "CN");
        assertTrue(msg.verify());
        assertEquals("CN=AdminCA1,O=EJBCA Sample,C=SE", msg.getIssuerDN());
        assertEquals("CN=abc123rry-4371939543913639881,O=PrimeKey Solutions AB,C=SE", msg.getRequestDN());
        assertEquals("abc123rry-4371939543913639881", msg.getUsername());
        assertEquals("foo123", msg.getPassword());
        // Verify PBE protection
        PKIHeader head = msg.getHeader();
        final ASN1OctetString os = head.getSenderKID();
        String keyId = CmpMessageHelper.getStringFromOctets(os);
        assertEquals("mykeyid", keyId);
        final CmpPbeVerifyer verifyer = new CmpPbeVerifyer(msg.getMessage());
        assertTrue(verifyer.verify("foo123"));
        assertFalse(verifyer.verify("bar123"));
    } finally {
        in.close();
    }
}

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

License:Open Source License

private void doNovosecClientRequest(final String sigAlg, final String digestAlg, final String expectedAlgOid)
        throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException,
        InvalidAlgorithmParameterException, SignatureException, IllegalStateException,
        OperatorCreationException, CertificateException {
    // Check that we can parse a request from  Novosec (patched by EJBCA).
    // Read an initialization request with a signature POP and signature protection to see that we can process it
    {/*from  ww w  .j  a va2  s  .  c o  m*/
        ASN1InputStream in = new ASN1InputStream(novosecsigpopir);
        try {
            ASN1Primitive derObject = in.readObject();
            PKIMessage req = PKIMessage.getInstance(derObject);
            //log.info(req.toString());
            // Verify should be ok if we do not allow RA verify POP here
            CrmfRequestMessage msg = new CrmfRequestMessage(req, "CN=AdminCA1", false, "CN");
            assertTrue(msg.verify());
            // Since we don't have RA POP we can't test for that...
            assertEquals("CN=AdminCA1,O=EJBCA Sample,C=SE", msg.getIssuerDN());
            assertEquals("CN=abc123rry2942812801980668853,O=PrimeKey Solutions AB,C=SE", msg.getRequestDN());
            assertEquals("abc123rry2942812801980668853", msg.getUsername());
            assertEquals("foo123", msg.getPassword());
            // Verify signature protection
            AlgorithmIdentifier algId = msg.getMessage().getHeader().getProtectionAlg();
            String oid = algId.getAlgorithm().getId();
            assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), oid);
            // Check that this is an old message, created before ECA-2104, using null instead of DERNull as algorithm parameters.
            ASN1Encodable pp = algId.getParameters();
            assertNull(pp);
            // Try to verify, it should work good even though the small bug in ECA-2104, since we don't use algorithm parameters for RSA-PKCS signatures
            PublicKey pubKey = msg.getRequestPublicKey();
            assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), pubKey));
            // Verify that our verification routine does not give positive result for any other keys
            KeyPair keys = KeyTools.genKeys("512", "RSA");
            assertFalse(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), keys.getPublic()));
        } finally {
            in.close();
        }
    }
    // Re-protect the message, now fixed by ECA-2104
    {
        ASN1InputStream in = new ASN1InputStream(novosecsigpopir);
        try {
            ASN1Primitive derObject = in.readObject();
            PKIMessage myPKIMessage = PKIMessage.getInstance(derObject);
            KeyPair keys = KeyTools.genKeys("512", "RSA");
            X509Certificate signCert = CertTools.genSelfCert("CN=CMP Sign Test", 3650, null, keys.getPrivate(),
                    keys.getPublic(), sigAlg, false);
            // Re-sign the message
            Collection<Certificate> signCertChain = new ArrayList<Certificate>();
            signCertChain.add(signCert);
            byte[] newmsg = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, keys.getPrivate(),
                    digestAlg, "BC");
            in.close();
            in = new ASN1InputStream(newmsg);
            derObject = in.readObject();
            PKIMessage pkimsg = PKIMessage.getInstance(derObject);
            // We have to do this twice, because Novosec caches ProtectedBytes in the PKIMessage object, so we need to 
            // encode it and re-decode it again to get the changes from ECA-2104 encoded correctly.
            // Not needed when simply signing a new message that you create, only when re-signing 
            newmsg = CmpMessageHelper.signPKIMessage(pkimsg, signCertChain, keys.getPrivate(), digestAlg, "BC");
            in.close();
            in = new ASN1InputStream(newmsg);
            derObject = in.readObject();
            pkimsg = PKIMessage.getInstance(derObject);
            AlgorithmIdentifier algId = pkimsg.getHeader().getProtectionAlg();
            String oid = algId.getAlgorithm().getId();
            assertEquals(expectedAlgOid, oid);
            // Check that we have DERNull and not plain java null as algorithm parameters.
            ASN1Encodable pp = algId.getParameters();
            assertNotNull(pp);
            assertEquals(DERNull.class.getName(), pp.getClass().getName());
            // Try to verify, also verify at the same time that encoding decoding of the signature works
            assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(pkimsg, keys.getPublic()));
            // Verify that our verification routine does not give positive result for any other keys
            CrmfRequestMessage msg = new CrmfRequestMessage(pkimsg, "CN=AdminCA1", false, "CN");
            assertTrue(msg.verify());
            PublicKey pubKey = msg.getRequestPublicKey();
            assertFalse(CmpMessageHelper.verifyCertBasedPKIProtection(pkimsg, pubKey));
        } finally {
            in.close();
        }
    }
}

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

License:Open Source License

private void internalBcRARequestTest(byte[] message) throws IOException, InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException, SignatureException {
    // Check that we can parse request from BouncyCastle version 1.46.
    // Read an initialization request with RAVerifiedPOP with PBE protection to see that we can process it
    ASN1InputStream in = new ASN1InputStream(message);
    try {//from  w  ww .j  a  va 2s  .com
        ASN1Primitive derObject = in.readObject();
        PKIMessage req = PKIMessage.getInstance(derObject);
        //log.info(req.toString());
        // Verify should be false if we do not allow RA verify POP here, since we don't have any normal POP
        CrmfRequestMessage msg = new CrmfRequestMessage(req, "CN=AdminCA1", false, "CN");
        assertFalse(msg.verify());
        // Verify should be ok when we allow RA verified POP
        msg = new CrmfRequestMessage(req, "CN=AdminCA1", true, "CN");
        assertTrue(msg.verify());
        assertEquals("CN=AdminCA1", msg.getIssuerDN());
        assertEquals("CN=user", msg.getRequestDN());
        assertEquals("user", msg.getUsername());
        // We should want a password
        assertEquals("foo123", msg.getPassword());
        // Verify PBE protection
        PKIHeader head = msg.getHeader();
        final ASN1OctetString os = head.getSenderKID();
        String keyId = CmpMessageHelper.getStringFromOctets(os);
        assertEquals("KeyId", keyId);
        final CmpPbeVerifyer verifyer = new CmpPbeVerifyer(msg.getMessage());
        assertTrue(verifyer.verify("password"));
        assertFalse(verifyer.verify("foo123"));
    } finally {
        in.close();
    }
}