Example usage for java.security Signature update

List of usage examples for java.security Signature update

Introduction

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

Prototype

public final void update(ByteBuffer data) throws SignatureException 

Source Link

Document

Updates the data to be signed or verified using the specified ByteBuffer.

Usage

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  w  w w .jav  a  2s. c  om*/
 * @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:zlicense.de.schlichtherle.xml.GenericCertificate.java

public final synchronized void verify(PublicKey paramPublicKey, Signature paramSignature)
        throws NullPointerException, GenericCertificateIsLockedException, PropertyVetoException,
        InvalidKeyException, SignatureException, GenericCertificateIntegrityException {
    if (paramPublicKey == null) {
        throw new NullPointerException("verificationKey");
    }// w ww  . j  a  v  a 2  s .  c o  m
    if (paramSignature == null) {
        throw new NullPointerException("verificationEngine");
    }
    PropertyChangeEvent localPropertyChangeEvent = new PropertyChangeEvent(this, "locked",
            Boolean.valueOf(isLocked()), Boolean.TRUE);
    if (isLocked()) {
        throw new GenericCertificateIsLockedException(localPropertyChangeEvent);
    }
    fireVetoableChange(localPropertyChangeEvent);
    try {
        byte[] arrayOfByte1 = getEncoded().getBytes("UTF-8");
        paramSignature.initVerify(paramPublicKey);
        paramSignature.update(arrayOfByte1);
        byte[] arrayOfByte2 = Base64.decodeBase64(getSignature().getBytes("US-ASCII"));
        if (!paramSignature.verify(arrayOfByte2)) {
            throw new GenericCertificateIntegrityException();
        }
        setSignatureAlgorithm(paramSignature.getAlgorithm());
        setSignatureEncoding("US-ASCII/Base64");
    } catch (UnsupportedEncodingException localUnsupportedEncodingException) {
        throw new AssertionError(localUnsupportedEncodingException);
    }
    this.locked = true;
    firePropertyChange(localPropertyChangeEvent);
}

From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java

public Object handleMessage(AuthenticationDataMessage message, Map<String, String> httpHeaders,
        HttpServletRequest request, HttpSession session) throws ServletException {
    LOG.debug("authentication data message received");

    if (null == message.authnCert) {
        /*/*ww  w  .j  a  va 2  s .c  o  m*/
         * Can be the case for future (Kids) eID cards that have some
         * certificates missing.
         */
        String msg = "authentication certificate not present";
        LOG.warn(msg);
        throw new ServletException(msg);
    }
    byte[] signatureValue = message.signatureValue;
    LOG.debug("authn signing certificate subject: " + message.authnCert.getSubjectX500Principal());
    PublicKey signingKey = message.authnCert.getPublicKey();

    if (this.sessionIdChannelBinding) {
        checkSessionIdChannelBinding(message, request);
        if (null == this.serverCertificate) {
            LOG.warn("adviced to use in combination with server certificate channel binding");
        }
    }

    ChannelBindingService channelBindingService = this.channelBindingServiceLocator.locateService();
    if (null != this.serverCertificate || null != channelBindingService) {
        LOG.debug("using server certificate channel binding");
    }

    if (false == this.sessionIdChannelBinding && null == this.serverCertificate
            && null == channelBindingService) {
        LOG.warn("not using any secure channel binding");
    }

    byte[] challenge;
    try {
        challenge = AuthenticationChallenge.getAuthnChallenge(session, this.maxMaturity);
    } catch (SecurityException e) {
        AuditService auditService = this.auditServiceLocator.locateService();
        if (null != auditService) {
            String remoteAddress = request.getRemoteAddr();
            auditService.authenticationError(remoteAddress, message.authnCert);
        }
        throw new ServletException("security error: " + e.getMessage(), e);
    }

    byte[] serverCertificateClientPOV = null;
    try {
        if (null != message.serverCertificate) {
            serverCertificateClientPOV = message.serverCertificate.getEncoded();
        }
    } catch (CertificateEncodingException e) {
        throw new ServletException("server cert decoding error: " + e.getMessage(), e);
    }
    /*
     * We validate the authentication contract using the client-side
     * communicated server SSL certificate in case of secure channel
     * binding.
     */
    AuthenticationContract authenticationContract = new AuthenticationContract(message.saltValue, this.hostname,
            this.inetAddress, message.sessionId, serverCertificateClientPOV, challenge);
    byte[] toBeSigned;
    try {
        toBeSigned = authenticationContract.calculateToBeSigned();
    } catch (IOException e) {
        throw new ServletException("IO error: " + e.getMessage(), e);
    }

    try {
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initVerify(signingKey);
        signature.update(toBeSigned);
        boolean result = signature.verify(signatureValue);
        if (false == result) {
            AuditService auditService = this.auditServiceLocator.locateService();
            if (null != auditService) {
                String remoteAddress = request.getRemoteAddr();
                auditService.authenticationError(remoteAddress, message.authnCert);
            }
            throw new SecurityException("authn signature incorrect");
        }
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException("algo error");
    } catch (InvalidKeyException e) {
        throw new SecurityException("authn key error");
    } catch (SignatureException e) {
        throw new SecurityException("signature error");
    }

    RequestContext requestContext = new RequestContext(session);
    String transactionMessage = requestContext.getTransactionMessage();
    if (null != transactionMessage) {
        LOG.debug("verifying TransactionMessage signature");
        byte[] transactionMessageSignature = message.transactionMessageSignature;
        if (null == transactionMessageSignature) {
            throw new SecurityException("missing TransactionMessage signature");
        }
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, signingKey);
            byte[] signatureDigestInfoValue = cipher.doFinal(transactionMessageSignature);
            ASN1InputStream aIn = new ASN1InputStream(signatureDigestInfoValue);
            DigestInfo signatureDigestInfo = new DigestInfo((ASN1Sequence) aIn.readObject());
            if (false == PLAIN_TEXT_DIGEST_ALGO_OID
                    .equals(signatureDigestInfo.getAlgorithmId().getObjectId().getId())) {
                throw new SecurityException("TransactionMessage signature algo OID incorrect");
            }
            if (false == Arrays.equals(transactionMessage.getBytes(), signatureDigestInfo.getDigest())) {
                throw new SecurityException("signed TransactionMessage incorrect");
            }
            LOG.debug("TransactionMessage signature validated");
        } catch (Exception e) {
            LOG.error("error verifying TransactionMessage signature", e);
            AuditService auditService = this.auditServiceLocator.locateService();
            if (null != auditService) {
                String remoteAddress = request.getRemoteAddr();
                auditService.authenticationError(remoteAddress, message.authnCert);
            }
            throw new SecurityException("error verifying TransactionMessage signature: " + e.getMessage());
        }
    }

    /*
     * Secure channel binding verification.
     */
    if (null != channelBindingService) {
        X509Certificate serverCertificate = channelBindingService.getServerCertificate();
        if (null == serverCertificate) {
            LOG.warn("could not verify secure channel binding as the server does not know its identity yet");
        } else {
            if (false == serverCertificate.equals(message.serverCertificate)) {
                AuditService auditService = this.auditServiceLocator.locateService();
                if (null != auditService) {
                    String remoteAddress = request.getRemoteAddr();
                    auditService.authenticationError(remoteAddress, message.authnCert);
                }
                throw new SecurityException("secure channel binding identity mismatch");
            }
            LOG.debug("secure channel binding verified");
        }
    } else {
        if (null != this.serverCertificate) {
            if (false == this.serverCertificate.equals(message.serverCertificate)) {
                AuditService auditService = this.auditServiceLocator.locateService();
                if (null != auditService) {
                    String remoteAddress = request.getRemoteAddr();
                    auditService.authenticationError(remoteAddress, message.authnCert);
                }
                throw new SecurityException("secure channel binding identity mismatch");
            }
            LOG.debug("secure channel binding verified");
        }
    }

    AuthenticationService authenticationService = this.authenticationServiceLocator.locateService();
    List<X509Certificate> certificateChain = new LinkedList<X509Certificate>();
    certificateChain.add(message.authnCert);
    certificateChain.add(message.citizenCaCert);
    certificateChain.add(message.rootCaCert);
    certificateChain.add(message.rrnCertificate);
    try {
        authenticationService.setHttpSessionObject(request.getSession());
        authenticationService.validateCertificateChain(certificateChain);
    } catch (ExpiredCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
    } catch (RevokedCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
    } catch (TrustCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
    } catch (CertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE);
    } catch (Exception e) {
        /*
         * We don't want to depend on the full JavaEE profile in this
         * artifact.
         */
        if ("javax.ejb.EJBException".equals(e.getClass().getName())) {
            Exception exception;
            try {
                Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException",
                        new Class[] {});
                exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {});
            } catch (Exception e2) {
                LOG.debug("error: " + e.getMessage(), e);
                throw new SecurityException("error retrieving the root cause: " + e2.getMessage());
            }
            if (exception instanceof ExpiredCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
            }
            if (exception instanceof RevokedCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
            }
            if (exception instanceof TrustCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
            }
            if (exception instanceof CertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE);
            }
        }
        throw new SecurityException("authn service error: " + e.getMessage());
    }

    String userId = UserIdentifierUtil.getUserId(message.authnCert);
    LOG.info("authenticated: " + userId + " @ " + request.getRemoteAddr());
    if (null != this.nrcidSecret) {
        userId = UserIdentifierUtil.getNonReversibleCitizenIdentifier(userId, this.nrcidOrgId, this.nrcidAppId,
                this.nrcidSecret);
    }
    /*
     * Some people state that you cannot use the national register number
     * without hashing. Problem is that hashing introduces hash collision
     * problems. The probability is very low, but what if it's your leg
     * they're cutting of because of a patient mismatch based on the SHA1 of
     * your national register number?
     */

    /*
     * Push authenticated used Id into the HTTP session.
     */
    session.setAttribute(AUTHENTICATED_USER_IDENTIFIER_SESSION_ATTRIBUTE, userId);

    EIdData eidData = (EIdData) session.getAttribute(IdentityDataMessageHandler.EID_SESSION_ATTRIBUTE);
    if (null == eidData) {
        eidData = new EIdData();
        session.setAttribute(IdentityDataMessageHandler.EID_SESSION_ATTRIBUTE, eidData);
    }
    eidData.identifier = userId;

    AuditService auditService = this.auditServiceLocator.locateService();
    if (null != auditService) {
        auditService.authenticated(userId);
    }

    boolean includeIdentity = requestContext.includeIdentity();
    boolean includeAddress = requestContext.includeAddress();
    boolean includeCertificates = requestContext.includeCertificates();
    boolean includePhoto = requestContext.includePhoto();

    /*
     * Also process the identity data in case it was requested.
     */
    if (includeIdentity) {
        if (null == message.identityData) {
            throw new ServletException("identity data not included while requested");
        }
    }
    if (includeAddress) {
        if (null == message.addressData) {
            throw new ServletException("address data not included while requested");
        }
    }
    if (includePhoto) {
        if (null == message.photoData) {
            throw new ServletException("photo data not included while requested");
        }
    }
    IdentityIntegrityService identityIntegrityService = this.identityIntegrityServiceLocator.locateService();
    if (null != identityIntegrityService) {
        if (null == message.rrnCertificate) {
            throw new ServletException("national registry certificate not included while requested");
        }
        List<X509Certificate> rrnCertificateChain = new LinkedList<X509Certificate>();
        rrnCertificateChain.add(message.rrnCertificate);
        rrnCertificateChain.add(message.rootCaCert);

        try {
            identityIntegrityService.checkNationalRegistrationCertificate(rrnCertificateChain);
        } catch (ExpiredCertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
        } catch (RevokedCertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
        } catch (TrustCertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
        } catch (CertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE);
        } catch (Exception e) {
            if ("javax.ejb.EJBException".equals(e.getClass().getName())) {
                Exception exception;
                try {
                    Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException",
                            new Class[] {});
                    exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {});
                } catch (Exception e2) {
                    LOG.debug("error: " + e.getMessage(), e);
                    throw new SecurityException("error retrieving the root cause: " + e2.getMessage());
                }
                if (exception instanceof ExpiredCertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
                }
                if (exception instanceof RevokedCertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
                }
                if (exception instanceof TrustCertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
                }
                if (exception instanceof CertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE);
                }
            }
            throw new SecurityException("error checking the NRN certificate: " + e.getMessage(), e);
        }

        PublicKey rrnPublicKey = message.rrnCertificate.getPublicKey();
        if (includeIdentity) {
            if (null == message.identitySignatureData) {
                throw new ServletException("identity signature data not included while requested");
            }
            verifySignature(message.rrnCertificate.getSigAlgName(), message.identitySignatureData, rrnPublicKey,
                    request, message.identityData);
        }
        if (includeAddress) {
            if (null == message.addressSignatureData) {
                throw new ServletException("address signature data not included while requested");
            }
            byte[] addressFile = trimRight(message.addressData);
            verifySignature(message.rrnCertificate.getSigAlgName(), message.addressSignatureData, rrnPublicKey,
                    request, addressFile, message.identitySignatureData);
        }
    }
    if (includeIdentity) {
        Identity identity = TlvParser.parse(message.identityData, Identity.class);
        if (false == UserIdentifierUtil.getUserId(message.authnCert).equals(identity.nationalNumber)) {
            throw new ServletException("national number mismatch");
        }
        session.setAttribute(IdentityDataMessageHandler.IDENTITY_SESSION_ATTRIBUTE, identity);
        eidData.identity = identity;
        auditService = this.auditServiceLocator.locateService();
        if (null != auditService) {
            auditService.identified(identity.nationalNumber);
        }
    }
    if (includeAddress) {
        Address address = TlvParser.parse(message.addressData, Address.class);
        session.setAttribute(IdentityDataMessageHandler.ADDRESS_SESSION_ATTRIBUTE, address);
        eidData.address = address;
    }
    if (includePhoto) {
        if (includeIdentity) {
            byte[] expectedPhotoDigest = eidData.identity.photoDigest;
            byte[] actualPhotoDigest = digestPhoto(getDigestAlgo(expectedPhotoDigest.length),
                    message.photoData);
            if (false == Arrays.equals(expectedPhotoDigest, actualPhotoDigest)) {
                throw new ServletException("photo digest incorrect");
            }
        }
        session.setAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE, message.photoData);
        eidData.photo = message.photoData;
    }
    if (includeCertificates) {
        if (includeIdentity) {
            eidData.certs = new EIdCertsData();
            eidData.certs.authn = message.authnCert;
            eidData.certs.ca = message.citizenCaCert;
            eidData.certs.root = message.rootCaCert;
            eidData.certs.sign = message.signCert;
        }
        session.setAttribute(IdentityDataMessageHandler.AUTHN_CERT_SESSION_ATTRIBUTE, message.authnCert);
        session.setAttribute(IdentityDataMessageHandler.CA_CERT_SESSION_ATTRIBUTE, message.citizenCaCert);
        session.setAttribute(IdentityDataMessageHandler.ROOT_CERT_SESSION_ATTRIBTUE, message.rootCaCert);
        session.setAttribute(IdentityDataMessageHandler.SIGN_CERT_SESSION_ATTRIBUTE, message.signCert);
    }

    if (this.includeDataFiles) {
        session.setAttribute(IdentityDataMessageHandler.EID_DATA_IDENTITY_SESSION_ATTRIBUTE,
                message.identityData);
        session.setAttribute(IdentityDataMessageHandler.EID_DATA_ADDRESS_SESSION_ATTRIBUTE,
                message.addressData);
    }

    AuthenticationSignatureService authenticationSignatureService = this.authenticationSignatureServiceLocator
            .locateService();
    if (null != authenticationSignatureService) {
        List<X509Certificate> authnCertificateChain;
        if (null != message.authnCert) {
            authnCertificateChain = new LinkedList<X509Certificate>();
            authnCertificateChain.add(message.authnCert);
            authnCertificateChain.add(message.citizenCaCert);
            authnCertificateChain.add(message.rootCaCert);
            authnCertificateChain.add(message.rrnCertificate);
        } else {
            authnCertificateChain = null;
        }
        AuthenticationSignatureContext authenticationSignatureContext = new AuthenticationSignatureContextImpl(
                session);
        PreSignResult preSignResult = authenticationSignatureService.preSign(authnCertificateChain,
                authenticationSignatureContext);
        if (null == preSignResult) {
            return new FinishedMessage();
        }
        boolean logoff = preSignResult.getLogoff();
        byte[] computedDigestValue = preSignResult.getDigestInfo().digestValue;
        String digestAlgo = preSignResult.getDigestInfo().digestAlgo;
        String authnMessage = preSignResult.getDigestInfo().description;
        AuthSignRequestMessage authSignRequestMessage = new AuthSignRequestMessage(computedDigestValue,
                digestAlgo, authnMessage, logoff);
        return authSignRequestMessage;
    }
    return new FinishedMessage();
}

From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java

private void verifySignature(String signatureAlgo, byte[] signatureData, PublicKey publicKey,
        HttpServletRequest request, byte[]... data) throws ServletException {
    Signature signature;
    try {/*from w w  w.  jav a  2  s  .c o  m*/
        signature = Signature.getInstance(signatureAlgo);
    } catch (NoSuchAlgorithmException e) {
        throw new ServletException("algo error: " + e.getMessage(), e);
    }
    try {
        signature.initVerify(publicKey);
    } catch (InvalidKeyException e) {
        throw new ServletException("key error: " + e.getMessage(), e);
    }
    try {
        for (byte[] dataItem : data) {
            signature.update(dataItem);
        }
        boolean result = signature.verify(signatureData);
        if (false == result) {
            AuditService auditService = this.auditServiceLocator.locateService();
            if (null != auditService) {
                String remoteAddress = request.getRemoteAddr();
                auditService.identityIntegrityError(remoteAddress);
            }
            throw new ServletException("signature incorrect");
        }
    } catch (SignatureException e) {
        throw new ServletException("signature error: " + e.getMessage(), e);
    }
}

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   www  .  ja  v a 2 s .  com*/
 * @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:Networking.Client.java

public boolean SignatureVerification() {
    Signature sig = null;
    Boolean result = false;/*from w  w  w .  j av a2 s . c om*/
    try {
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(PubToVerify);
        KeyFactory keyFact = KeyFactory.getInstance("DSA", "SUN");
        PublicKey pubkeyToVerify = keyFact.generatePublic(pubKeySpec);
        confirmIdentity = checkAgainstRT(pubkeyToVerify.hashCode());
        sig = Signature.getInstance("SHA1withDSA", "SUN");
        sig.initVerify(pubkeyToVerify);

        byte[] g_pow_y_sign = this.node.getG_pow_y().toByteArray();
        byte[] g_pow_x_sign = this.node.getG_pow_x().toByteArray();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(g_pow_x_sign);
        outputStream.write(g_pow_y_sign);
        byte[] c = outputStream.toByteArray();

        sig.update(c);
        result = (sig.verify(sigToVerify));
    } catch (SignatureException | InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException
            | InvalidKeySpecException | IOException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

/**
 * Sign data with the specified elliptic curve private key.
 *
 * @param privateKey elliptic curve private key.
 * @param data       data to sign/*from ww w .  ja va  2 s  .c o  m*/
 * @return the signed data.
 * @throws CryptoException
 */
private byte[] ecdsaSignToBytes(ECPrivateKey privateKey, byte[] data) throws CryptoException {
    if (data == null) {
        throw new CryptoException("Data that to be signed is null.");
    }
    if (data.length == 0) {
        throw new CryptoException("Data to be signed was empty.");
    }

    try {
        X9ECParameters params = ECNamedCurveTable.getByName(curveName);
        BigInteger curveN = params.getN();

        Signature sig = SECURITY_PROVIDER == null ? Signature.getInstance(DEFAULT_SIGNATURE_ALGORITHM)
                : Signature.getInstance(DEFAULT_SIGNATURE_ALGORITHM, SECURITY_PROVIDER);
        sig.initSign(privateKey);
        sig.update(data);
        byte[] signature = sig.sign();

        BigInteger[] sigs = decodeECDSASignature(signature);

        sigs = preventMalleability(sigs, curveN);

        try (ByteArrayOutputStream s = new ByteArrayOutputStream()) {

            DERSequenceGenerator seq = new DERSequenceGenerator(s);
            seq.addObject(new ASN1Integer(sigs[0]));
            seq.addObject(new ASN1Integer(sigs[1]));
            seq.close();
            return s.toByteArray();
        }

    } catch (Exception e) {
        throw new CryptoException("Could not sign the message using private key", e);
    }

}

From source file:org.dasein.security.joyent.SignatureHttpAuth.java

@Override
public void addPreemptiveAuth(@Nonnull HttpRequest request) throws CloudException, InternalException {
    if (provider.getContext() == null) {
        throw new CloudException("No context was defined for this request");
    }//www . j  a  v  a  2 s  .  c  o m
    Date date = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
    String now = RFC1123_DATE_FORMAT.format(date);
    request.setHeader("Date", now);
    try {
        Security.addProvider(new BouncyCastleProvider());
        Signature signature = Signature.getInstance(SIGN_ALGORITHM);

        List<ContextRequirements.Field> fields = provider.getContextRequirements().getConfigurableValues();
        String keyName = "";
        String privateKey = "";
        char[] keyPassword = null;
        for (ContextRequirements.Field f : fields) {
            if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) {
                byte[][] keyPair = (byte[][]) provider.getContext().getConfigurationValue(f);
                keyName = new String(keyPair[0], "utf-8");
                privateKey = new String(keyPair[1], "utf-8");
            } else if (f.type.equals(ContextRequirements.FieldType.PASSWORD)) {
                byte[] password = (byte[]) provider.getContext().getConfigurationValue(f);
                if (password != null) {
                    keyPassword = new String(password, "utf-8").toCharArray();
                }
            }
        }

        signature.initSign(getKeyPair(privateKey, keyPassword).getPrivate());
        String signingString = String.format(AUTH_SIGN, now);
        signature.update(signingString.getBytes("UTF-8"));
        byte[] signedDate = signature.sign();
        byte[] encodedSignedDate = Base64.encode(signedDate);

        request.addHeader("Authorization", String.format(AUTH_HEADER, provider.getContext().getAccountNumber(),
                keyName, new String(encodedSignedDate)));

    } catch (NoSuchAlgorithmException e) {
        throw new InternalException(e);
    } catch (UnsupportedEncodingException e) {
        throw new InternalException(e);
    } catch (SignatureException e) {
        throw new InternalException(e);
    } catch (InvalidKeyException e) {
        throw new InternalException(e);
    } catch (IOException e) {
        throw new InternalException(e);
    }
}

From source file:com.vmware.identity.samlservice.impl.SamlServiceImpl.java

@Override
public void verifySignature(String message, String signature) throws IllegalStateException {

    Validate.notNull(this.getCheckAlgorithm());
    Validate.notNull(this.getCertPath());

    boolean verifies = false;
    try {/*www  .j av a 2s  .  c o m*/
        /* create a Signature object and initialize it with the public key */
        Signature sig = Signature.getInstance(this.getCheckAlgorithm().getAlgorithmName());
        X509Certificate[] chain = this.getCertPath().getCertificates().toArray(new X509Certificate[0]);

        for (int i = 0; i < chain.length && !verifies; i++) {
            sig.initVerify(chain[i].getPublicKey());

            /* add buffer to verify */
            byte[] buffer = message.getBytes("UTF-8");
            sig.update(buffer);

            byte[] sigToVerify = Base64.decode(signature);

            verifies = sig.verify(sigToVerify);
            if (!verifies) {
                log.error("Unable to verify the signature, message " + message + ", sigAlg "
                        + this.getCheckAlgorithm().getAlgorithmName() + ", signature " + signature);
            }
        }

        log.debug("signature verifies: {}", verifies);
    } catch (Exception e) {
        log.error("Caught exception while verifying signature, message: " + message + ", sigAlg "
                + this.getCheckAlgorithm().getAlgorithmName() + ", signature " + signature);
        log.error("Exception is: {}", e.toString());
        throw new IllegalStateException(e);
    }
    if (!verifies) {
        throw new IllegalStateException("Signature verification failed.");
    }
}

From source file:test.be.fedict.eid.applet.PcscTest.java

@Test
public void pcscAuthnSignature() throws Exception {
    this.messages = new Messages(Locale.GERMAN);
    PcscEid pcscEid = new PcscEid(new TestView(), this.messages);
    if (false == pcscEid.isEidPresent()) {
        LOG.debug("insert eID card");
        pcscEid.waitForEidPresent();//from  ww  w  .j a  va2 s. c  om
    }
    byte[] challenge = "hello world".getBytes();
    byte[] signatureValue;
    List<X509Certificate> authnCertChain;
    try {
        // pcscEid.logoff();
        // pcscEid.selectBelpicJavaCardApplet();
        signatureValue = pcscEid.signAuthn(challenge);

        long t0 = System.currentTimeMillis();
        pcscEid.signAuthn(challenge);
        long t1 = System.currentTimeMillis();
        LOG.debug("dt: " + (t1 - t0));

        authnCertChain = pcscEid.getAuthnCertificateChain();
        LOG.debug("key size: " + authnCertChain.get(0).getPublicKey().getEncoded().length * 8);
        // pcscEid.logoff();
    } finally {
        pcscEid.close();
    }

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(authnCertChain.get(0).getPublicKey());
    signature.update(challenge);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);
    LOG.debug("sha1 hex: " + DigestUtils.shaHex(authnCertChain.get(0).getPublicKey().getEncoded()));
}