Example usage for java.security Signature getInstance

List of usage examples for java.security Signature getInstance

Introduction

In this page you can find the example usage for java.security Signature getInstance.

Prototype

public static Signature getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Signature object that implements the specified signature algorithm.

Usage

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static boolean verifySignatureES384(byte[] signingInput, byte[] sigBytes, ECDSAPublicKey ecdsaPublicKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        IOException, SignatureException {
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-384");
    BigInteger q = ((ECCurve.Fp) ecSpec.getCurve()).getQ();
    ECFieldElement xFieldElement = new ECFieldElement.Fp(q, ecdsaPublicKey.getX());
    ECFieldElement yFieldElement = new ECFieldElement.Fp(q, ecdsaPublicKey.getY());
    ECPoint pointQ = new ECPoint.Fp(ecSpec.getCurve(), xFieldElement, yFieldElement);
    ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(pointQ, ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    Signature signature = Signature.getInstance("SHA384WITHECDSA", "BC");
    signature.initVerify(publicKey);// w  w w  . j  av a  2 s  .c o m
    signature.update(signingInput);
    return signature.verify(sigBytes);
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static boolean verifySignatureES384(byte[] signingInput, byte[] sigBytes, X509Certificate cert)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    PublicKey publicKey = cert.getPublicKey();

    Signature signature = Signature.getInstance("SHA384WITHECDSA", "BC");
    signature.initVerify(publicKey);/*from w  w  w . j ava  2s  . c  o m*/
    signature.update(signingInput);
    return signature.verify(sigBytes);
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static boolean verifySignatureES512(byte[] signingInput, byte[] sigBytes, ECDSAPublicKey ecdsaPublicKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        IOException, SignatureException {
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-521");
    BigInteger q = ((ECCurve.Fp) ecSpec.getCurve()).getQ();
    ECFieldElement xFieldElement = new ECFieldElement.Fp(q, ecdsaPublicKey.getX());
    ECFieldElement yFieldElement = new ECFieldElement.Fp(q, ecdsaPublicKey.getY());
    ECPoint pointQ = new ECPoint.Fp(ecSpec.getCurve(), xFieldElement, yFieldElement);
    ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(pointQ, ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    Signature signature = Signature.getInstance("SHA512WITHECDSA", "BC");
    signature.initVerify(publicKey);// w w  w. jav  a 2s . co  m
    signature.update(signingInput);
    return signature.verify(sigBytes);
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static boolean verifySignatureES512(byte[] signingInput, byte[] sigBytes, X509Certificate cert)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    PublicKey publicKey = cert.getPublicKey();

    Signature signature = Signature.getInstance("SHA512WITHECDSA", "BC");
    signature.initVerify(publicKey);/*from   ww  w .jav  a2 s.  c o  m*/
    signature.update(signingInput);
    return signature.verify(sigBytes);
}

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

/**
 * 1- Sends a CRMF request signed by RA2Admin to RA1. Expected: Fail
 * 2- Sends a CRMF request signed by RA1Admin to RA2. Expected: Fail
 * //from   ww w  .j av a 2s.co  m
 * @throws Exception
 */
@Test
public void test01RA1FailedCRMF() throws Exception {

    // Send CRMF message signed by RA2Admin to RA1
    String testUsername = "ra1testuser";
    X500Name testUserDN = new X500Name("CN=" + testUsername);
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage msg = genCertReq(ca1.getSubjectDN(), testUserDN, keys, ca1.getCACertificate(), nonce, transid,
            false, null, null, null, null, pAlg, new DEROctetString(nonce));
    assertNotNull("Generating CrmfRequest failed.", msg);

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

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(msg);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, RA1_ALIAS);
    checkCmpResponseGeneral(resp, ca1.getSubjectDN(), testUserDN, ca1.getCACertificate(),
            msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false,
            null, null);
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    PKIMessage respObject = null;
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull("Reading CMP response failed.", respObject);
    PKIBody body = respObject.getBody();
    assertEquals(PKIBody.TYPE_ERROR, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    String expectedErrMsg = "'CN=" + RA2_ADMIN + "' is not an authorized administrator.";
    assertEquals(expectedErrMsg, errMsg);

    // Send CRMF message signed by RA1Admin to RA2
    testUsername = "ra2testuser";
    testUserDN = new X500Name("CN=" + testUsername);
    keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    msg = genCertReq(ca2.getSubjectDN(), testUserDN, keys, ca2.getCACertificate(), nonce, transid, false, null,
            null, null, null, pAlg, new DEROctetString(nonce));
    assertNotNull("Generating CrmfRequest failed.", msg);

    extraCert = getCMPCert(ra1admincert);
    msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra1adminkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull("Signing CMP message failed.", msg);
    //******************************************''''''
    sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC");
    sig.initVerify(ra1admincert.getPublicKey());
    sig.update(CmpMessageHelper.getProtectedBytes(msg));
    verified = sig.verify(msg.getProtection().getBytes());
    assertTrue("Signing the message failed.", verified);
    //***************************************************

    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(msg);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, RA2_ALIAS);
    checkCmpResponseGeneral(resp, ca2.getSubjectDN(), testUserDN, ca2.getCACertificate(),
            msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false,
            null, null);
    asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull("Reading CMP response failed.", respObject);
    body = respObject.getBody();
    assertEquals(PKIBody.TYPE_ERROR, body.getType());
    err = (ErrorMsgContent) body.getContent();
    errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    expectedErrMsg = "'CN=" + RA1_ADMIN + "' is not an authorized administrator.";
    assertEquals(expectedErrMsg, errMsg);

}

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

@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);/*from   www . j a va2s .co  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);
}

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

protected static void checkCmpResponseGeneral(byte[] retMsg, String issuerDN, X500Name userDN,
        Certificate cacert, byte[] senderNonce, byte[] transId, boolean signed, String pbeSecret,
        String expectedSignAlg)//w ww.j  a v a  2 s  .c  o m
        throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    assertNotNull("No response from server.", retMsg);
    assertTrue("Response was of 0 length.", retMsg.length > 0);
    boolean pbe = (pbeSecret != null);
    //
    // Parse response message
    //
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg));
    PKIMessage respObject = null;
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    // The signer, i.e. the CA, check it's the right CA
    PKIHeader header = respObject.getHeader();

    // Check that the message is signed with the correct digest alg
    if (StringUtils.isEmpty(expectedSignAlg)) {
        expectedSignAlg = PKCSObjectIdentifiers.sha1WithRSAEncryption.getId();
    }
    // if cacert is ECDSA we should expect an ECDSA signature alg
    //if (AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECDSA")) {
    //    expectedSignAlg = X9ObjectIdentifiers.ecdsa_with_SHA1.getId();
    //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECGOST3410")) {
    //    expectedSignAlg = CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001.getId();
    //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("DSTU4145")) {
    //    expectedSignAlg = (new ASN1ObjectIdentifier(CesecoreConfiguration.getOidDstu4145())).getId();
    //}
    if (signed) {
        AlgorithmIdentifier algId = header.getProtectionAlg();
        assertNotNull(
                "Protection algorithm was null when expecting a signed response, this was propably an unprotected error message: "
                        + header.getFreeText(),
                algId);
        assertEquals(expectedSignAlg, algId.getAlgorithm().getId());
    }
    if (pbe) {
        AlgorithmIdentifier algId = header.getProtectionAlg();
        assertNotNull(
                "Protection algorithm was null when expecting a pbe protected response, this was propably an unprotected error message: "
                        + header.getFreeText(),
                algId);
        assertEquals("Protection algorithm id: " + algId.getAlgorithm().getId(),
                CMPObjectIdentifiers.passwordBasedMac.getId(), algId.getAlgorithm().getId()); // 1.2.840.113549.1.1.5 - SHA-1 with RSA Encryption
    }

    // Check that the signer is the expected CA    
    assertEquals(header.getSender().getTagNo(), 4);

    X500Name expissuer = new X500Name(issuerDN);
    X500Name actissuer = new X500Name(header.getSender().getName().toString());
    assertEquals(expissuer, actissuer);
    if (signed) {
        // Verify the signature
        byte[] protBytes = CmpMessageHelper.getProtectedBytes(respObject);
        DERBitString bs = respObject.getProtection();
        Signature sig;
        try {
            sig = Signature.getInstance(expectedSignAlg, "BC");
            sig.initVerify(cacert);
            sig.update(protBytes);
            boolean ret = sig.verify(bs.getBytes());
            assertTrue(ret);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (SignatureException e) {
            e.printStackTrace();
            assertTrue(false);
        }
    }
    if (pbe) {
        ASN1OctetString os = header.getSenderKID();
        assertNotNull(os);
        String keyId = CmpMessageHelper.getStringFromOctets(os);
        log.debug("Found a sender keyId: " + keyId);
        // Verify the PasswordBased protection of the message
        byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(respObject);
        DERBitString protection = respObject.getProtection();
        AlgorithmIdentifier pAlg = header.getProtectionAlg();
        log.debug("Protection type is: " + pAlg.getAlgorithm().getId());
        PBMParameter pp = PBMParameter.getInstance(pAlg.getParameters());
        int iterationCount = pp.getIterationCount().getPositiveValue().intValue();
        log.debug("Iteration count is: " + iterationCount);
        AlgorithmIdentifier owfAlg = pp.getOwf();
        // Normal OWF alg is 1.3.14.3.2.26 - SHA1
        log.debug("Owf type is: " + owfAlg.getAlgorithm().getId());
        AlgorithmIdentifier macAlg = pp.getMac();
        // Normal mac alg is 1.3.6.1.5.5.8.1.2 - HMAC/SHA1
        log.debug("Mac type is: " + macAlg.getAlgorithm().getId());
        byte[] salt = pp.getSalt().getOctets();
        // log.info("Salt is: "+new String(salt));
        byte[] raSecret = pbeSecret != null ? pbeSecret.getBytes() : new byte[0];
        byte[] basekey = new byte[raSecret.length + salt.length];
        System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
        for (int i = 0; i < salt.length; i++) {
            basekey[raSecret.length + i] = salt[i];
        }
        // Construct the base key according to rfc4210, section 5.1.3.1
        MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(),
                BouncyCastleProvider.PROVIDER_NAME);
        for (int i = 0; i < iterationCount; i++) {
            basekey = dig.digest(basekey);
            dig.reset();
        }
        // HMAC/SHA1 os normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7
        String macOid = macAlg.getAlgorithm().getId();
        Mac mac = Mac.getInstance(macOid, BouncyCastleProvider.PROVIDER_NAME);
        SecretKey key = new SecretKeySpec(basekey, macOid);
        mac.init(key);
        mac.reset();
        mac.update(protectedBytes, 0, protectedBytes.length);
        byte[] out = mac.doFinal();
        // My out should now be the same as the protection bits
        byte[] pb = protection.getBytes();
        boolean ret = Arrays.equals(out, pb);
        assertTrue(ret);
    }

    // --SenderNonce
    // SenderNonce is something the server came up with, but it should be 16
    // chars
    byte[] nonce = header.getSenderNonce().getOctets();
    assertEquals(nonce.length, 16);

    // --Recipient Nonce
    // recipient nonce should be the same as we sent away as sender nonce
    nonce = header.getRecipNonce().getOctets();
    assertEquals(new String(nonce), new String(senderNonce));

    // --Transaction ID
    // transid should be the same as the one we sent
    nonce = header.getTransactionID().getOctets();
    assertEquals(new String(nonce), new String(transId));

}

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

/**
 * Sends a KeyUpdateRequest with a different key and the configurations is NOT to allow the use of the same keys. 
 * Successful operation is expected and a new certificate is received.
 * /*  ww  w . j  av a  2  s  . co m*/
 * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal)
 * - Pre-configuration: Sets cmp.allowautomaticrenewal to 'true' and tests that the resetting of configuration has worked.
 * - Pre-configuration: Sets cmp.allowupdatewithsamekey to 'false'
 * - 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
 * - Sends the request using HTTP and receives a 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 test06UpdateWithDifferentKey() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">test08UpdateWithDifferentKey");
    }

    this.cmpConfiguration.setRAMode(this.cmpAlias, false);
    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, false);
    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;
    certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123",
            new PublicKeyWrapper(keys.getPublic()));
    assertNotNull("Failed to create a test certificate", certificate);

    KeyPair newkeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, newkeys, false, null,
            null, pAlg, new DEROctetString(this.nonce));
    assertNotNull("Failed to generate a CMP renewal request", req);
    CertReqMessages kur = (CertReqMessages) req.getBody().getContent();
    int reqId = kur.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();

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

    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, true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkKurCertRepMessage(this.userDN, this.cacert, resp, reqId);
    assertNotNull("Failed to renew the certificate", cert);
    assertTrue("The new certificate's keys are incorrect.", cert.getPublicKey().equals(newkeys.getPublic()));
    assertFalse("The new certificate's keys are the same as the old certificate's keys.",
            cert.getPublicKey().equals(keys.getPublic()));

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

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

@Test
public void test12EECrmfNotCheckAdmin()
        throws NoSuchAlgorithmException, EjbcaException, IOException, Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.cmpConfiguration.setOmitVerificationsInECC(ALIAS, true);
    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, new DEROctetString(this.nonce));
    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);/*from w  ww  .  j ava  2 s  .c  om*/

    //********************************************
    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(), false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        PKIMessage respObject = PKIMessage.getInstance(inputStream.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 = "Omitting some verifications can only be accepted in RA mode and when the CMP request has already been authenticated, for example, through the use of NestedMessageContent";
        assertEquals(expectedErrmsg, errMsg);
    } finally {
        inputStream.close();
    }
    removeAuthenticationToken(adminToken, admCert, adminName);

}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Testing a key pair to verify that it is possible to first sign and then verify with it.
 * //from  w w w. j av  a2s  . c  o m
 * @param priv
 *            private key to sign a string with
 * @param pub
 *            public key to verify the signature with
 * @param provider
 *            A provider used for signing with the private key, or null if "BC" should be used.
 * 
 * @throws InvalidKeyException
 *             if the public key can not be used to verify a string signed by the private key, because the key is wrong or the signature operation
 *             fails for other reasons such as a NoSuchAlgorithmException or SignatureException.
 * @throws NoSuchProviderException
 *             if the provider is not installed.
 */
public static void testKey(final PrivateKey priv, final PublicKey pub, final String provider)
        throws InvalidKeyException { // NOPMD:this is not a junit test
    final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes();
    final byte signBV[];
    final String testSigAlg;
    {
        final Iterator<String> i = AlgorithmTools.getSignatureAlgorithms(pub).iterator();
        final String tmp = i.hasNext() ? i.next() : null;
        testSigAlg = tmp != null ? tmp : "SHA1WithRSA";
    }
    if (log.isDebugEnabled()) {
        log.debug("Testing keys with algorithm: " + pub.getAlgorithm());
        log.debug("testSigAlg: " + testSigAlg);
        log.debug("provider: " + provider);
        log.trace("privateKey: " + priv);
        log.trace("privateKey class: " + priv.getClass().getName());
        log.trace("publicKey: " + pub);
        log.trace("publicKey class: " + pub.getClass().getName());
    }
    try {
        {
            final Provider prov = Security.getProvider(provider != null ? provider : "BC");
            final Signature signature = Signature.getInstance(testSigAlg, prov);
            signature.initSign(priv);
            signature.update(input);
            signBV = signature.sign();
            if (signBV == null) {
                throw new InvalidKeyException("Result from signing is null.");
            }
            if (log.isDebugEnabled()) {
                log.trace("Created signature of size: " + signBV.length);
                log.trace("Created signature: " + new String(Hex.encode(signBV)));
            }
        }
        {
            Signature signature;
            try {
                signature = Signature.getInstance(testSigAlg, "BC");
            } catch (NoSuchProviderException e) {
                throw new IllegalStateException("BouncyCastle was not found as a provider.", e);
            }
            signature.initVerify(pub);
            signature.update(input);
            if (!signature.verify(signBV)) {
                throw new InvalidKeyException("Not possible to sign and then verify with key pair.");
            }
        }
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e);
    } catch (SignatureException e) {
        throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e);
    }
}