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.ejbca.ui.cmpclient.commands.CrmfRequestCommand.java

@Override
public PKIMessage generatePKIMessage(final ParameterContainer parameters) throws Exception {

    final boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY));
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));

    String authmodule = parameters.get(AUTHENTICATION_MODULE_KEY);
    String endentityPassword = "";
    if (authmodule != null && StringUtils.equals(authmodule, CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD)) {
        endentityPassword = parameters.containsKey(AUTHENTICATION_PARAM_KEY)
                ? parameters.get(AUTHENTICATION_PARAM_KEY)
                : "foo123";
    }// www  . ja va2s. c  om

    String altNames = parameters.get(ALTNAME_KEY);
    String serno = parameters.get(SERNO_KEY);
    BigInteger customCertSerno = null;
    if (serno != null) {
        customCertSerno = new BigInteger(serno, 16);
    }
    boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY);

    if (verbose) {
        log.info("Creating CRMF request with: SubjectDN=" + userDN.toString());
        log.info("Creating CRMF request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating CRMF request with: AuthenticationModule=" + authmodule);
        log.info("Creating CRMF request with: EndEntityPassword=" + endentityPassword);
        log.info("Creating CRMF request with: SubjectAltName=" + altNames);
        log.info("Creating CRMF request with: CustomCertSerno="
                + (customCertSerno == null ? "" : customCertSerno.toString(16)));
        log.info("Creating CRMF request with: IncludePopo=" + includePopo);
    }

    final KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
    final byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    final byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();

    // We should be able to back date the start time when allow validity
    // override is enabled in the certificate profile
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_WEEK, -1);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    // in validity
    Date notBefore = cal.getTime();
    cal.add(Calendar.DAY_OF_WEEK, 3);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(notBefore);
    // in validity
    Date notAfter = cal.getTime();
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(notAfter);

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    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);
    if (issuerDN != null) {
        myCertTemplate.setIssuer(issuerDN);
    }
    myCertTemplate.setSubject(userDN);
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
    dIn.close();
    myCertTemplate.setPublicKey(keyInfo);

    // Create standard extensions
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream dOut = new ASN1OutputStream(bOut);
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    if (altNames != null) {
        GeneralNames san = CertTools.getGeneralNamesFromAltName(altNames);
        dOut.writeObject(san);
        byte[] value = bOut.toByteArray();
        extgen.addExtension(Extension.subjectAlternativeName, false, value);
    }

    // KeyUsage
    int bcku = 0;
    bcku = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation;
    KeyUsage ku = new KeyUsage(bcku);
    extgen.addExtension(Extension.keyUsage, false, new DERBitString(ku));

    // Make the complete extension package
    Extensions exts = extgen.generate();

    myCertTemplate.setExtensions(exts);
    if (customCertSerno != null) {
        // Add serialNumber to the certTemplate, it is defined as a MUST NOT be used in RFC4211, but we will use it anyway in order
        // to request a custom certificate serial number (something not standard anyway)
        myCertTemplate.setSerialNumber(new ASN1Integer(customCertSerno));
    }

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

    // POPO
    /*
     * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8,
     * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 }));
     * 
     * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new
     * byte[] { 44 }), 2); //take choice pos tag 2
     * 
     * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput(
     * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2,
     * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 }));
     */
    ProofOfPossession myProofOfPossession = null;
    if (includePopo) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEROutputStream mout = new DEROutputStream(baos);
        mout.writeObject(myCertRequest);
        mout.close();
        byte[] popoProtectionBytes = baos.toByteArray();
        String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm())
                .getId();
        Signature sig = Signature.getInstance(sigalg, "BC");
        sig.initSign(keys.getPrivate());
        sig.update(popoProtectionBytes);
        DERBitString bs = new DERBitString(sig.sign());
        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    } else {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    }

    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(endentityPassword));
    AttributeTypeAndValue[] avs = { av };

    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN));

    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(null);
    myPKIHeader.setSenderKID(new byte[0]);

    PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization
    // request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    return myPKIMessage;
}

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

@Override
public boolean verify() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    boolean ret = false;
    final ProofOfPossession pop = getReq().getPopo();
    if (log.isDebugEnabled()) {
        log.debug("allowRaVerifyPopo: " + allowRaVerifyPopo);
        log.debug("pop.getRaVerified(): " + (pop.getType() == ProofOfPossession.TYPE_RA_VERIFIED));
    }/*from  w ww . j  a v  a  2s .c  om*/
    if (allowRaVerifyPopo && (pop.getType() == ProofOfPossession.TYPE_RA_VERIFIED)) {
        ret = true;
    } else if (pop.getType() == ProofOfPossession.TYPE_SIGNING_KEY) {
        try {
            final POPOSigningKey sk = (POPOSigningKey) pop.getObject();
            final POPOSigningKeyInput pski = sk.getPoposkInput();
            ASN1Encodable protObject = pski;
            // Use of POPOSigningKeyInput or not, as described in RFC4211, section 4.1.
            if (pski == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Using CertRequest as POPO input because POPOSigningKeyInput is missing.");
                }
                protObject = getReq().getCertReq();
            } else {
                // Assume POPOSigningKeyInput with the public key and name, MUST be the same as in the request according to RFC4211
                if (log.isDebugEnabled()) {
                    log.debug("Using POPOSigningKeyInput as POPO input.");
                }
                final CertRequest req = getReq().getCertReq();
                // If subject is present in cert template it must be the same as in POPOSigningKeyInput
                final X500Name subject = req.getCertTemplate().getSubject();
                if (subject != null && !subject.toString().equals(pski.getSender().getName().toString())) {
                    log.info("Subject '" + subject.toString() + "', is not equal to '"
                            + pski.getSender().toString() + "'.");
                    protObject = null; // pski is not a valid protection object
                }
                // If public key is present in cert template it must be the same as in POPOSigningKeyInput
                final SubjectPublicKeyInfo pk = req.getCertTemplate().getPublicKey();
                if (pk != null && !Arrays.areEqual(pk.getEncoded(), pski.getPublicKey().getEncoded())) {
                    log.info(
                            "Subject key in cert template, is not equal to subject key in POPOSigningKeyInput.");
                    protObject = null; // pski is not a valid protection object
                }
            }
            // If a protectObject is present we extract the bytes and verify it
            if (protObject != null) {
                final ByteArrayOutputStream bao = new ByteArrayOutputStream();
                new DEROutputStream(bao).writeObject(protObject);
                final byte[] protBytes = bao.toByteArray();
                final AlgorithmIdentifier algId = sk.getAlgorithmIdentifier();
                if (log.isDebugEnabled()) {
                    log.debug(
                            "POP protection bytes length: " + (protBytes != null ? protBytes.length : "null"));
                    log.debug("POP algorithm identifier is: " + algId.getAlgorithm().getId());
                }
                final Signature sig = Signature.getInstance(algId.getAlgorithm().getId(), "BC");
                sig.initVerify(getRequestPublicKey());
                sig.update(protBytes);
                final DERBitString bs = sk.getSignature();
                ret = sig.verify(bs.getBytes());
                if (log.isDebugEnabled()) {
                    log.debug("POP verify returns: " + ret);
                }
            }
        } catch (IOException e) {
            log.error("Error encoding CertReqMsg: ", e);
        } catch (SignatureException e) {
            log.error("SignatureException verifying POP: ", e);
        }
    }
    return ret;
}

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

public static byte[] getSignatureRS512(byte[] signingInput, RSAPrivateKey rsaPrivateKey)
        throws SignatureException, InvalidKeyException, NoSuchProviderException, InvalidKeySpecException,
        NoSuchAlgorithmException {
    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(),
            rsaPrivateKey.getPrivateExponent());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    PrivateKey privateKey = keyFactory.generatePrivate(rsaPrivateKeySpec);

    Signature signature = Signature.getInstance("SHA512withRSA", "BC");
    signature.initSign(privateKey);//from   w  ww  . java 2 s  .com
    signature.update(signingInput);

    return signature.sign();
}

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

@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  a v  a  2  s  . 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.xdi.oxauth.model.util.JwtUtil.java

public static byte[] getSignatureES256(byte[] signingInput, ECDSAPrivateKey ecdsaPrivateKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException,
        SignatureException {/* w  w w. j ava  2s.c o m*/
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-256");
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(ecdsaPrivateKey.getD(), ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    Signature signature = Signature.getInstance("SHA256WITHECDSA", "BC");
    signature.initSign(privateKey);
    signature.update(signingInput);

    return signature.sign();
}

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

public static byte[] getSignatureES384(byte[] signingInput, ECDSAPrivateKey ecdsaPrivateKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException,
        SignatureException {//from   w  w w . j a va 2  s . c o  m
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-384");
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(ecdsaPrivateKey.getD(), ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    Signature signature = Signature.getInstance("SHA384WITHECDSA", "BC");
    signature.initSign(privateKey);
    signature.update(signingInput);

    return signature.sign();
}

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

public static byte[] getSignatureES512(byte[] signingInput, ECDSAPrivateKey ecdsaPrivateKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException,
        SignatureException {//from   ww  w.j av a 2  s.  c  o m
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-521");
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(ecdsaPrivateKey.getD(), ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    Signature signature = Signature.getInstance("SHA512WITHECDSA", "BC");
    signature.initSign(privateKey);
    signature.update(signingInput);

    return signature.sign();
}

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

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

    // Send CRMF message signed by RA1Admin to RA1
    String testUsername = "ra1testuser";
    String fingerprintCert = null;
    try {

        final 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(ra1admincert);
        msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra1adminkeys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull("Signing CMP message failed", msg);
        //******************************************''''''
        final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
                "BC");
        sig.initVerify(ra1admincert.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, RA1_ALIAS);
        checkCmpResponseGeneral(resp, ca1.getSubjectDN(), testUserDN, ca1.getCACertificate(),
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
        Certificate cert = checkCmpCertRepMessage(testUserDN, (X509Certificate) ca1.getCACertificate(), resp,
                ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
        assertNotNull("CrmfRequest did not return a certificate", cert);
        fingerprintCert = CertTools.getFingerprintAsString(cert);
    } finally {
        internalCertStoreSession.removeCertificate(fingerprintCert);
        endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused);
    }

    // Send CRMF message signed by RA2Admin to RA2
    testUsername = "ra2testuser";
    try {

        final X500Name testUserDN = new X500Name("CN=" + testUsername);
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genCertReq(ca2.getSubjectDN(), testUserDN, keys, ca2.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);
        //******************************************''''''
        final 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);
        //***************************************************

        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, RA2_ALIAS);
        checkCmpResponseGeneral(resp, ca2.getSubjectDN(), testUserDN, ca2.getCACertificate(),
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
        Certificate cert = checkCmpCertRepMessage(testUserDN, (X509Certificate) ca2.getCACertificate(), resp,
                ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
        assertNotNull("CrmfRequest did not return a certificate", cert);
        fingerprintCert = CertTools.getFingerprintAsString(cert);
    } finally {
        internalCertStoreSession.removeCertificate(fingerprintCert);
        endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused);
    }

}

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

public static boolean verifySignatureES256(byte[] signingInput, byte[] sigBytes, ECDSAPublicKey ecdsaPublicKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        IOException, SignatureException {
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-256");
    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("SHA256WITHECDSA", "BC");
    signature.initVerify(publicKey);/* w  w  w.j  ava2  s  .c  o m*/
    signature.update(signingInput);
    return signature.verify(sigBytes);
}

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

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

    Signature signature = Signature.getInstance("SHA256WITHECDSA", "BC");
    signature.initVerify(publicKey);//from w w  w  .j  a v a  2s .c om
    signature.update(signingInput);
    return signature.verify(sigBytes);
}