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:test.unit.be.fedict.eid.applet.service.AuthenticationDataMessageHandlerTest.java

public void testHandleMessageNRCID() throws Exception {
    // setup//from   w w  w.java 2s  . com
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    String userId = "1234";
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(),
            "CN=Test, SERIALNUMBER=" + userId, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null,
            null);

    byte[] salt = "salt".getBytes();
    byte[] sessionId = "session-id".getBytes();

    AuthenticationDataMessage message = new AuthenticationDataMessage();
    message.authnCert = certificate;
    message.saltValue = salt;
    message.sessionId = sessionId;

    Map<String, String> httpHeaders = new HashMap<String, String>();
    HttpSession testHttpSession = new HttpTestSession();
    HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class);
    ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class);

    byte[] challenge = AuthenticationChallenge.generateChallenge(testHttpSession);

    AuthenticationContract authenticationContract = new AuthenticationContract(salt, null, null, sessionId,
            null, challenge);
    byte[] toBeSigned = authenticationContract.calculateToBeSigned();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(keyPair.getPrivate());
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();
    message.signatureValue = signatureValue;

    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.CHALLENGE_MAX_MATURITY_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(AuthenticationTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.HOSTNAME_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INET_ADDRESS_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(AuditTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVER_CERTIFICATE))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(HelloMessageHandler.SESSION_ID_CHANNEL_BINDING_INIT_PARAM_NAME))
            .andStubReturn(null);
    String nrcidSecret = "112233445566778899AABBCCDDEEFF00112233445566778899";
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME))
            .andStubReturn(nrcidSecret);
    String nrcidAppId = "my-app-id";
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_APP_ID_INIT_PARAM_NAME))
            .andStubReturn(nrcidAppId);
    String nrcidOrgId = "my-org-id";
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_ORG_ID_INIT_PARAM_NAME))
            .andStubReturn(nrcidOrgId);

    EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session"))
            .andStubReturn(new String(Hex.encodeHex(sessionId)));
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_IDENTITY_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_CERTS_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_ADDRESS_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_PHOTO_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME + "Class"))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE + "Class"))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);
    EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("1.2.3.4");
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(
            AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(null);

    // prepare
    EasyMock.replay(mockServletRequest, mockServletConfig);

    // operate
    AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance);
    this.testedInstance.init(mockServletConfig);
    this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, testHttpSession);

    // verify
    EasyMock.verify(mockServletRequest, mockServletConfig);
    assertTrue(AuthenticationTestService.isCalled());

    String nrcid = UserIdentifierUtil.getNonReversibleCitizenIdentifier(userId, nrcidOrgId, nrcidAppId,
            nrcidSecret);

    assertTrue(nrcid.equals(AuditTestService.getAuditUserId()));
    assertTrue(nrcid.equals(testHttpSession.getAttribute("eid.identifier")));
}

From source file:test.unit.be.fedict.eid.applet.service.AuthenticationDataMessageHandlerTest.java

@Test
public void testHandleMessageExpiredChallenge() throws Exception {
    // setup//from  w ww .  j  a  v a 2s  .com
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    String userId = "1234";
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(),
            "CN=Test, SERIALNUMBER=" + userId, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null,
            null);

    byte[] salt = "salt".getBytes();
    byte[] sessionId = "session-id".getBytes();

    AuthenticationDataMessage message = new AuthenticationDataMessage();
    message.authnCert = certificate;
    message.saltValue = salt;
    message.sessionId = sessionId;

    Map<String, String> httpHeaders = new HashMap<String, String>();
    HttpSession testHttpSession = new HttpTestSession();
    HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class);
    ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class);

    byte[] challenge = AuthenticationChallenge.generateChallenge(testHttpSession);

    Thread.sleep(1000); // > 1 ms

    AuthenticationContract authenticationContract = new AuthenticationContract(salt, null, null, sessionId,
            null, challenge);
    byte[] toBeSigned = authenticationContract.calculateToBeSigned();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(keyPair.getPrivate());
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();
    message.signatureValue = signatureValue;

    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.CHALLENGE_MAX_MATURITY_INIT_PARAM_NAME))
            .andReturn("1"); // 1 ms
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(AuthenticationTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.HOSTNAME_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INET_ADDRESS_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVER_CERTIFICATE))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(HelloMessageHandler.SESSION_ID_CHANNEL_BINDING_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_IDENTITY_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_CERTS_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_ADDRESS_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_PHOTO_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME + "Class"))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(AuditTestService.class.getName());
    EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("remote-address");

    EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session"))
            .andStubReturn(new String(Hex.encodeHex(sessionId)));
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE + "Class"))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_ORG_ID_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_APP_ID_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(
            AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(null);

    // prepare
    EasyMock.replay(mockServletRequest, mockServletConfig);

    // operate
    AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance);
    this.testedInstance.init(mockServletConfig);
    try {
        this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, testHttpSession);
        fail();
    } catch (ServletException e) {
        // verify
        EasyMock.verify(mockServletRequest, mockServletConfig);
        assertNull(AuditTestService.getAuditUserId());
        assertNull(testHttpSession.getAttribute("eid.identifier"));
        assertEquals(certificate, AuditTestService.getAuditClientCertificate());
        assertEquals("remote-address", AuditTestService.getAuditRemoteAddress());
    }
}

From source file:test.unit.be.fedict.eid.applet.service.AuthenticationDataMessageHandlerTest.java

@Test
public void testInvalidAuthenticationSignature() throws Exception {
    // setup//from  w  ww  . j  av a  2 s .  co  m
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    String userId = "1234";
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(),
            "CN=Test, SERIALNUMBER=" + userId, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null,
            null);

    byte[] salt = "salt".getBytes();
    byte[] sessionId = "session-id".getBytes();

    AuthenticationDataMessage message = new AuthenticationDataMessage();
    message.authnCert = certificate;
    message.saltValue = salt;
    message.sessionId = sessionId;

    Map<String, String> httpHeaders = new HashMap<String, String>();
    HttpSession testHttpSession = new HttpTestSession();
    HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class);
    ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class);

    AuthenticationChallenge.generateChallenge(testHttpSession);

    AuthenticationContract authenticationContract = new AuthenticationContract(salt, null, null, sessionId,
            null, "foobar-challenge".getBytes());
    byte[] toBeSigned = authenticationContract.calculateToBeSigned();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(keyPair.getPrivate());
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();
    message.signatureValue = signatureValue;

    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.CHALLENGE_MAX_MATURITY_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(AuthenticationTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.HOSTNAME_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INET_ADDRESS_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVER_CERTIFICATE))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(HelloMessageHandler.SESSION_ID_CHANNEL_BINDING_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(AuditTestService.class.getName());
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_IDENTITY_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_CERTS_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_ADDRESS_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_PHOTO_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME + "Class"))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE + "Class"))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_ORG_ID_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_APP_ID_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(
            AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(null);

    EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session"))
            .andStubReturn(new String(Hex.encodeHex(sessionId)));

    String remoteAddress = "1.2.3.4";
    EasyMock.expect(mockServletRequest.getRemoteAddr()).andReturn(remoteAddress);

    // prepare
    EasyMock.replay(mockServletRequest, mockServletConfig);

    // operate
    AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance);
    this.testedInstance.init(mockServletConfig);

    try {
        this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, testHttpSession);
        fail();
    } catch (SecurityException e) {
        // expected
    }

    // verify
    EasyMock.verify(mockServletRequest, mockServletConfig);
    assertFalse(AuthenticationTestService.isCalled());
    assertNull(AuditTestService.getAuditUserId());
    assertEquals(remoteAddress, AuditTestService.getAuditRemoteAddress());
    assertEquals(certificate, AuditTestService.getAuditClientCertificate());
    assertNull(testHttpSession.getAttribute("eid.identifier"));
}

From source file:cl.nic.dte.util.XMLUtil.java

public static AUTORIZACIONDocument generateAuthorization(AUTORIZACIONDocument template, PrivateKey pKey)
        throws NoSuchAlgorithmException, SignatureException, TransformerException, InvalidKeyException,
        IOException {/*from   w w  w.  j  av a2s  .  c  o m*/
    // Generation of keys

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024);
    KeyPair kp = kpg.generateKeyPair();

    CAFType caf = template.getAUTORIZACION().getCAF();
    CAFType.DA.RSAPK rsapk = caf.getDA().addNewRSAPK();

    rsapk.setM(((RSAPublicKey) kp.getPublic()).getModulus().toByteArray());
    rsapk.setE(((RSAPublicKey) kp.getPublic()).getPublicExponent().toByteArray());

    ResourceBundle labels = ResourceBundle.getBundle("cl.nic.dte.resources.VerifyResults");

    Signature sig = null;
    if (pKey.getAlgorithm().equals("RSA")) {
        sig = Signature.getInstance("SHA1withRSA");
        caf.addNewFRMA().setAlgoritmo("SHA1withRSA");
    } else if (pKey.getAlgorithm().equals("DSA")) {
        sig = Signature.getInstance("SHA1withDSA");
        caf.addNewFRMA().setAlgoritmo("SHA1withDSA");
    } else {
        throw new NoSuchAlgorithmException(
                labels.getString("ALGORITHM_NOT_SUPPORTED").replaceAll("%1", pKey.getAlgorithm()));
    }

    template.getAUTORIZACION()
            .setRSASK("-----BEGIN RSA PRIVATE KEY-----\n"
                    + new String(Base64.encodeBase64(kp.getPrivate().getEncoded(), true))
                    + "-----END RSA PRIVATE KEY-----\n");

    template.getAUTORIZACION()
            .setRSAPUBK("-----BEGIN RSA PUBLIC KEY-----\n"
                    + new String(Base64.encodeBase64(kp.getPublic().getEncoded(), true))
                    + "-----END RSA PUBLIC KEY-----\n");

    sig.initSign(pKey);
    sig.update(XMLUtil.getCleaned(caf.getDA()));

    caf.getFRMA().setByteArrayValue(Base64.encodeBase64(sig.sign()));
    return template;
}

From source file:org.waveprotocol.wave.crypto.WaveSignatureVerifier.java

/**
 * Verifies the signature on some signed payload.
 * @param signedPayload the payload on which we're verifiying the signature.
 * @param signatureInfo the signature provided with the payload.
 * @param authority name of the authority that we expect the target
 *   certificate to be issued to./*  www  . ja v  a2  s  .  c o m*/
 *
 * @throws SignatureException if the signature can't be verified, either
 *   because it simply didn't check out, or because of other reasons, like us
 *   not supporting the signature algorithm specified.
 * @throws UnknownSignerException if we can't find the cert chain in the local
 *   cert-path store.
 */
public void verify(byte[] signedPayload, ProtocolSignature signatureInfo, String authority)
        throws SignatureException, UnknownSignerException {

    SignerInfo signer = pathStore.getSignerInfo(signatureInfo.getSignerId().toByteArray());

    if (signer == null) {
        throw new UnknownSignerException("could not find information about signer "
                + Base64.encodeBase64(signatureInfo.getSignerId().toByteArray()));
    }

    verifySignerInfo(signer);

    Signature verifier;
    try {
        verifier = Signature.getInstance(AlgorithmUtil.getJceName(signatureInfo.getSignatureAlgorithm()));
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException(
                "can't verify signatures of type " + signatureInfo.getSignatureAlgorithm().toString(), e);
    }

    X509Certificate cert = signer.getCertificates().get(0);

    try {
        verifier.initVerify(cert);
    } catch (InvalidKeyException e) {
        throw new SignatureException("certificate of signer was not issued for " + "message signing");
    }

    try {
        verifier.update(signedPayload);
    } catch (java.security.SignatureException e) {
        // this is thrown if the verifier object is not properly initialized.
        // this shouldn't happen as we _just_ initialized it on the previous line.
        throw new IllegalStateException(e);
    }

    try {
        if (!verifier.verify(signatureInfo.getSignatureBytes().toByteArray())) {
            throw new SignatureException("signature did not verify");
        }
    } catch (java.security.SignatureException e) {
        throw new SignatureException(e);
    }

    verifyMatchingAuthority(authority, cert);
}

From source file:org.wso2.carbon.appmgt.impl.token.JWTGenerator.java

/**
   * Helper method to sign the JWT/* w ww  .  java  2s  .  c om*/
   *
   * @param assertion
   * @param endUserName
   * @return signed assertion
   * @throws org.wso2.carbon.appmgt.api.AppManagementException
   */
private byte[] signJWT(String assertion, String endUserName) throws AppManagementException {

    try {
        //get tenant domain
        String tenantDomain = MultitenantUtils.getTenantDomain(endUserName);
        //get tenantId
        int tenantId = getTenantId(endUserName);

        Key privateKey = null;

        if (!(privateKeys.containsKey(tenantId))) {
            AppManagerUtil.loadTenantRegistry(tenantId);
            //get tenant's key store manager
            KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

            if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                //derive key store name
                String ksName = tenantDomain.trim().replace(".", "-");
                String jksName = ksName + ".jks";
                //obtain private key
                //TODO: maintain a hash map with tenants' private keys after first initialization
                privateKey = tenantKSM.getPrivateKey(jksName, tenantDomain);
            } else {
                try {
                    privateKey = tenantKSM.getDefaultPrivateKey();
                } catch (Exception e) {
                    log.error("Error while obtaining private key for super tenant", e);
                }
            }
            if (privateKey != null) {
                privateKeys.put(tenantId, privateKey);
            }
        } else {
            privateKey = privateKeys.get(tenantId);
        }

        //initialize signature with private key and algorithm
        Signature signature = Signature.getInstance(signatureAlgorithm);
        signature.initSign((PrivateKey) privateKey);

        //update signature with data to be signed
        byte[] dataInBytes = assertion.getBytes();
        signature.update(dataInBytes);

        //sign the assertion and return the signature
        byte[] signedInfo = signature.sign();
        return signedInfo;

    } catch (NoSuchAlgorithmException e) {
        String error = "Signature algorithm not found.";
        //do not log
        throw new AppManagementException(error);
    } catch (InvalidKeyException e) {
        String error = "Invalid private key provided for the signature";
        //do not log
        throw new AppManagementException(error);
    } catch (SignatureException e) {
        String error = "Error in signature";
        //do not log
        throw new AppManagementException(error);
    } catch (AppManagementException e) {
        //do not log
        throw new AppManagementException(e.getMessage());
    }
}

From source file:com.tremolosecurity.idp.providers.Saml2Idp.java

private void procAuthnReq(HttpServletRequest request, HttpServletResponse response,
        DocumentBuilderFactory factory, String saml, String relayState) throws ParserConfigurationException,
        SAXException, IOException, UnmarshallingException, Exception, UnsupportedEncodingException,
        NoSuchAlgorithmException, InvalidKeyException, SignatureException, ServletException {
    AuthnRequestUnmarshaller marshaller = new AuthnRequestUnmarshaller();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Element root = builder.parse(new InputSource(new StringReader(saml))).getDocumentElement();

    AuthnRequest authn = (AuthnRequest) marshaller.unmarshall(root);

    String issuer = authn.getIssuer().getValue();

    String authnCtx = null;//from w w w  .  ja  v  a  2s.c o m

    if (authn.getRequestedAuthnContext() == null
            || authn.getRequestedAuthnContext().getAuthnContextClassRefs().size() == 0
            || authn.getRequestedAuthnContext().getAuthnContextClassRefs().get(0)
                    .getAuthnContextClassRef() == null) {
        //no authnCtx information, use default
        authnCtx = null;
    } else {
        authnCtx = authn.getRequestedAuthnContext().getAuthnContextClassRefs().get(0).getAuthnContextClassRef();
    }

    String nameID = null;

    if (authn.getNameIDPolicy() == null) {
        nameID = null;
    } else {
        nameID = authn.getNameIDPolicy().getFormat();
    }

    String binding = authn.getProtocolBinding();
    String url = authn.getAssertionConsumerServiceURL();

    if (logger.isDebugEnabled()) {
        logger.debug("Issuer : '" + issuer + "'");
        logger.debug("Binding : '" + binding + "'");
        logger.debug("URL : '" + url + "'");

        logger.debug("NameID Format : '" + nameID + "'");
        logger.debug("Authn Class Ctx : '" + authnCtx + "'");
    }

    Saml2Trust trust = this.trusts.get(issuer);

    if (trust == null) {
        StringBuffer b = new StringBuffer();
        b.append("Could not find a trust for issuer '").append(issuer).append("'");
        throw new Exception(b.toString());
    }

    String authnSig = request.getParameter("Signature");
    if (authnSig != null) {
        String sigAlg = request.getParameter("SigAlg");
        StringBuffer query = new StringBuffer();
        query.append("SAMLRequest=").append(URLEncoder.encode(request.getParameter("SAMLRequest"), "UTF-8"));
        if (relayState != null) {
            query.append("&RelayState=").append(URLEncoder.encode(relayState, "UTF-8"));
        }
        query.append("&SigAlg=").append(URLEncoder.encode(sigAlg, "UTF-8"));

        String validationCert = trust.spSigCert;
        UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
        java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(validationCert);

        if (!Saml2Idp.xmlDigSigAlgs.containsKey(sigAlg)) {
            throw new Exception("Invalid signature algorithm : " + sigAlg);
        }

        if (!authn.getDestination().equals(request.getRequestURL().toString())) {
            throw new Exception("Invalid destination");
        }

        Signature sigv = Signature.getInstance(Saml2Idp.javaDigSigAlgs.get(sigAlg));

        sigv.initVerify(cert.getPublicKey());
        sigv.update(query.toString().getBytes("UTF-8"));

        if (!sigv.verify(Base64.decodeBase64(authnSig.getBytes("UTF-8")))) {
            throw new Exception("Signature verification failed");
        }

    } else if (this.requireSignedAuthn) {
        throw new Exception("No signature on the authentication request");
    }

    doFederation(request, response, issuer, nameID, authnCtx, url, relayState, trust);
}

From source file:org.structr.util.StructrLicenseManager.java

private boolean verify(final byte[] data, final byte[] signatureData) {

    try {//  ww  w. ja v a2 s.c  o  m

        final Signature verifier = Signature.getInstance(SignatureAlgorithm);

        verifier.initVerify(certificate);
        verifier.update(data);

        if (verifier.verify(signatureData)) {

            return true;
        }

    } catch (Throwable t) {
        logger.warn("Unable to verify volume license: {}", t.getMessage());
    }

    logger.error("License verification failed, license is not valid.");

    return false;
}

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

private void verifySignature(String signAlgo, byte[] signatureData, PublicKey publicKey,
        HttpServletRequest request, byte[]... data) throws ServletException {
    Signature signature;
    try {/*www.ja va  2s .c o  m*/
        signature = Signature.getInstance(signAlgo);
    } 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) {
        AuditService auditService = this.auditServiceLocator.locateService();
        if (null != auditService) {
            String remoteAddress = request.getRemoteAddr();
            auditService.identityIntegrityError(remoteAddress);
        }
        throw new ServletException("signature error: " + e.getMessage(), e);
    }
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

public static Properties readCredentials(DataInputStream dis, DataOutputStream dos, DistributedSystem system,
        SecurityService securityService) throws GemFireSecurityException, IOException {

    boolean requireAuthentication = securityService.isClientSecurityRequired();
    Properties credentials = null;
    try {//from  ww w .j av a 2s.c  om
        byte secureMode = dis.readByte();
        throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE);
        if (secureMode == CREDENTIALS_NORMAL) {
            if (requireAuthentication) {
                credentials = DataSerializer.readProperties(dis);
            } else {
                DataSerializer.readProperties(dis); // ignore the credentials
            }
        } else if (secureMode == CREDENTIALS_DHENCRYPT) {
            boolean sendAuthentication = dis.readBoolean();
            InternalLogWriter securityLogWriter = (InternalLogWriter) system.getSecurityLogWriter();
            // Get the symmetric encryption algorithm to be used
            String skAlgo = DataSerializer.readString(dis);
            // Get the public key of the other side
            byte[] keyBytes = DataSerializer.readByteArray(dis);
            byte[] challenge = null;
            PublicKey pubKey = null;
            if (requireAuthentication) {
                // Generate PublicKey from encoded form
                X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
                KeyFactory keyFact = KeyFactory.getInstance("DH");
                pubKey = keyFact.generatePublic(x509KeySpec);

                // Send the public key to other side
                keyBytes = dhPublicKey.getEncoded();
                challenge = new byte[64];
                random.nextBytes(challenge);

                // If the server has to also authenticate itself then
                // sign the challenge from client.
                if (sendAuthentication) {
                    // Get the challenge string from client
                    byte[] clientChallenge = DataSerializer.readByteArray(dis);
                    if (privateKeyEncrypt == null) {
                        throw new AuthenticationFailedException(
                                LocalizedStrings.HandShake_SERVER_PRIVATE_KEY_NOT_AVAILABLE_FOR_CREATING_SIGNATURE
                                        .toLocalizedString());
                    }
                    // Sign the challenge from client and send it to the client
                    Signature sig = Signature.getInstance(privateKeySignAlgo);
                    sig.initSign(privateKeyEncrypt);
                    sig.update(clientChallenge);
                    byte[] signedBytes = sig.sign();
                    dos.writeByte(REPLY_OK);
                    DataSerializer.writeByteArray(keyBytes, dos);
                    // DataSerializer.writeString(privateKeyAlias, dos);
                    DataSerializer.writeString(privateKeySubject, dos);
                    DataSerializer.writeByteArray(signedBytes, dos);
                    securityLogWriter.fine("HandShake: sent the signed client challenge");
                } else {
                    // These two lines should not be moved before the if{} statement in
                    // a common block for both if...then...else parts. This is to handle
                    // the case when an AuthenticationFailedException is thrown by the
                    // if...then part when sending the signature.
                    dos.writeByte(REPLY_OK);
                    DataSerializer.writeByteArray(keyBytes, dos);
                }
                // Now send the server challenge
                DataSerializer.writeByteArray(challenge, dos);
                securityLogWriter.fine("HandShake: sent the public key and challenge");
                dos.flush();

                // Read and decrypt the credentials
                byte[] encBytes = DataSerializer.readByteArray(dis);
                KeyAgreement ka = KeyAgreement.getInstance("DH");
                ka.init(dhPrivateKey);
                ka.doPhase(pubKey, true);

                Cipher decrypt;

                int keysize = getKeySize(skAlgo);
                int blocksize = getBlockSize(skAlgo);

                if (keysize == -1 || blocksize == -1) {
                    SecretKey sKey = ka.generateSecret(skAlgo);
                    decrypt = Cipher.getInstance(skAlgo);
                    decrypt.init(Cipher.DECRYPT_MODE, sKey);
                } else {
                    String algoStr = getDhAlgoStr(skAlgo);

                    byte[] sKeyBytes = ka.generateSecret();
                    SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, algoStr);
                    IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize);

                    decrypt = Cipher.getInstance(algoStr + "/CBC/PKCS5Padding");
                    decrypt.init(Cipher.DECRYPT_MODE, sks, ivps);
                }

                byte[] credentialBytes = decrypt.doFinal(encBytes);
                ByteArrayInputStream bis = new ByteArrayInputStream(credentialBytes);
                DataInputStream dinp = new DataInputStream(bis);
                credentials = DataSerializer.readProperties(dinp);
                byte[] challengeRes = DataSerializer.readByteArray(dinp);
                // Check the challenge string
                if (!Arrays.equals(challenge, challengeRes)) {
                    throw new AuthenticationFailedException(
                            LocalizedStrings.HandShake_MISMATCH_IN_CHALLENGE_BYTES_MALICIOUS_CLIENT
                                    .toLocalizedString());
                }
                dinp.close();
            } else {
                if (sendAuthentication) {
                    // Read and ignore the client challenge
                    DataSerializer.readByteArray(dis);
                }
                dos.writeByte(REPLY_AUTH_NOT_REQUIRED);
                dos.flush();
            }
        } else if (secureMode == SECURITY_MULTIUSER_NOTIFICATIONCHANNEL) {
            // hitesh there will be no credential CCP will get credential(Principal) using
            // ServerConnection..
            logger.debug("readCredential where multiuser mode creating callback connection");
        }
    } catch (IOException ex) {
        throw ex;
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationFailedException(
                LocalizedStrings.HandShake_FAILURE_IN_READING_CREDENTIALS.toLocalizedString(), ex);
    }
    return credentials;
}