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.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));
    }//w  ww  .j  av  a 2  s  .c  o  m
    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:be.fedict.eid.applet.service.impl.handler.SignCertificatesDataMessageHandler.java

private void verifySignature(String signatureAlgoName, byte[] signatureData, PublicKey publicKey,
        HttpServletRequest request, byte[]... data) throws ServletException {
    Signature signature;
    try {// w ww . j  a  va 2s.  c  om
        signature = Signature.getInstance(signatureAlgoName);
    } 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.wso2.carbon.appmgt.gateway.token.AbstractJWTGenerator.java

/**
 * Helper method to sign the JWT/* w w w .jav a 2 s.  co  m*/
 *
 * @param assertion Assertion
 * @param endUserName End user name
 * @return signed assertion
 * @throws AppManagementException on error while trying to sign JWT
 */
private byte[] signJWT(String assertion, String endUserName) throws AppManagementException {
    int tenantId = getTenantId(endUserName);
    try {
        Key privateKey = getPrivateKey(endUserName, tenantId);
        if (privateKey == null) {
            throw new AppManagementException("Private key is null for tenant " + 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(StandardCharsets.UTF_8);
        signature.update(dataInBytes);

        /* Sign the assertion and return the signature */
        byte[] signedInfo = signature.sign();
        return signedInfo;
    } catch (NoSuchAlgorithmException e) {
        String error = "Signature algorithm " + signatureAlgorithm + " not found.";
        log.error(error, e);
        throw new AppManagementException(error, e);
    } catch (InvalidKeyException e) {
        String error = "Invalid private key provided for the signature for tenant " + tenantId;
        log.error(error, e);
        throw new AppManagementException(error, e);
    } catch (SignatureException e) {
        String error = "Error in signature algorithm " + signatureAlgorithm;
        log.error(error, e);
        throw new AppManagementException(error, e);
    } catch (AppManagementException e) {
        String error = "Error in obtaining tenant's " + tenantId + " private key";
        log.error(error, e);
        throw new AppManagementException(error, e);
    }
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

/**
 * Sign a hash using the user's private key
 * /*from w  ww  . j  a va2s.  co m*/
 * @param hash
 * @param key
 * @return
 * @throws Exception
 */
public byte[] signHash(byte[] hash, String password) throws Exception {

    String alg = config.getProperty(RepositoryManagedSignatureProviderFactory.SIGNATURE_ALGORITHM);
    String prov = config.getProperty(RepositoryManagedSignatureProviderFactory.JAVA_SIGNATURE_PROVIDER);
    String alias = config.getProperty(RepositoryManagedSignatureProviderFactory.ALIAS);

    KeyStore ks = getUserKeyStore(password);
    PrivateKey key = (PrivateKey) ks.getKey(alias, password.toCharArray());
    Signature signer = Signature.getInstance(alg, prov);
    signer.initSign(key);
    signer.update(hash);
    return signer.sign();
}

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

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

    byte[] signatureValue = message.signatureValue;
    List<X509Certificate> certificateChain = message.certificateChain;
    if (certificateChain.isEmpty()) {
        throw new ServletException("certificate chain is empty");
    }//from   w  w  w  .j  a va2s .c o  m
    X509Certificate signingCertificate = certificateChain.get(0);
    if (null == signingCertificate) {
        throw new ServletException("non-repudiation certificate missing");
    }
    LOG.debug("non-repudiation signing certificate: " + signingCertificate.getSubjectX500Principal());

    for (X509Certificate certificate : certificateChain) {
        LOG.debug("signing x509 cert: " + certificate.getSubjectX500Principal());

    }
    PublicKey signingPublicKey = signingCertificate.getPublicKey();

    /*
     * Verify the signature.
     */
    String digestAlgo = SignatureDataMessageHandler.getDigestAlgo(session);
    byte[] expectedDigestValue = SignatureDataMessageHandler.getDigestValue(session);
    if (digestAlgo.endsWith("-PSS")) {
        LOG.debug("verifying RSA/PSS signature");
        try {
            Signature signature = Signature.getInstance("RAWRSASSA-PSS", BouncyCastleProvider.PROVIDER_NAME);
            if ("SHA-256-PSS".equals(digestAlgo)) {
                LOG.debug("RSA/PSS SHA256");
                signature.setParameter(
                        new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1));
            }
            signature.initVerify(signingPublicKey);
            signature.update(expectedDigestValue);
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage(), e);
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    } else {
        try {
            Signature signature = Signature.getInstance("RawRSA", BouncyCastleProvider.PROVIDER_NAME);
            signature.initVerify(signingPublicKey);
            ByteArrayOutputStream digestInfo = new ByteArrayOutputStream();
            if ("SHA-1".equals(digestAlgo) || "SHA1".equals(digestAlgo)) {
                digestInfo.write(SHA1_DIGEST_INFO_PREFIX);
            } else if ("SHA-224".equals(digestAlgo)) {
                digestInfo.write(SHA224_DIGEST_INFO_PREFIX);
            } else if ("SHA-256".equals(digestAlgo)) {
                digestInfo.write(SHA256_DIGEST_INFO_PREFIX);
            } else if ("SHA-384".equals(digestAlgo)) {
                digestInfo.write(SHA384_DIGEST_INFO_PREFIX);
            } else if ("SHA-512".equals(digestAlgo)) {
                digestInfo.write(SHA512_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD160".equals(digestAlgo)) {
                digestInfo.write(RIPEMD160_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD128".equals(digestAlgo)) {
                digestInfo.write(RIPEMD128_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD256".equals(digestAlgo)) {
                digestInfo.write(RIPEMD256_DIGEST_INFO_PREFIX);
            }
            digestInfo.write(expectedDigestValue);
            signature.update(digestInfo.toByteArray());
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                AuditService auditService = this.auditServiceLocator.locateService();
                if (null != auditService) {
                    String remoteAddress = request.getRemoteAddr();
                    auditService.signatureError(remoteAddress, signingCertificate);
                }
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage());
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    }

    AuditService auditService = this.auditServiceLocator.locateService();
    if (null != auditService) {
        String userId = UserIdentifierUtil.getUserId(signingCertificate);
        auditService.signed(userId);
    }

    SignatureService signatureService = this.signatureServiceLocator.locateService();
    try {
        signatureService.setHttpSessionObject(request.getSession());
        signatureService.postSign(signatureValue, 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("signature service error: " + e.getMessage(), e);
    }

    return new FinishedMessage();
}

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

private void verifySignature(BeIDContextQualifier contextQualifier, String signAlgo, byte[] signatureData,
        X509Certificate certificate, HttpServletRequest request, byte[]... data) throws ServletException {
    Signature signature;
    try {//from   ww  w  .j a v a  2 s  .c  om
        signature = Signature.getInstance(signAlgo);
    } catch (NoSuchAlgorithmException e) {
        throw new ServletException("algo error: " + e.getMessage(), e);
    }
    PublicKey publicKey = certificate.getPublicKey();
    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) {
            SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.DATA_INTEGRITY, certificate,
                    signatureData);
            this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
            throw new ServletException("signature incorrect");
        }
    } catch (SignatureException e) {
        SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.DATA_INTEGRITY, certificate,
                signatureData);
        this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
        throw new ServletException("signature error: " + e.getMessage(), e);
    }
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

@Override
public boolean validateSignature(byte[] sig, byte[] hash) {
    String alg = config.getProperty(RepositoryManagedSignatureProviderFactory.SIGNATURE_ALGORITHM);
    String prov = config.getProperty(RepositoryManagedSignatureProviderFactory.JAVA_SIGNATURE_PROVIDER);

    boolean valid = false;

    try {//from w w w  . j  a  va  2s  . c  o  m
        Signature validate = Signature.getInstance(alg, prov);
        validate.initVerify(getPublicKey());
        validate.update(hash);
        valid = validate.verify(sig);
    } catch (NoSuchProviderException nspe) {
        throw new AlfrescoRuntimeException("Provider: " + prov + " was not found: " + nspe.getMessage());
    } catch (NoSuchAlgorithmException nsae) {
        throw new AlfrescoRuntimeException("Algorithm: " + alg + " is not available: " + nsae.getMessage());
    } catch (SignatureException se) {
        valid = false;
    } catch (InvalidKeyException ike) {
        valid = false;
    }

    return valid;
}

From source file:uk.bowdlerize.API.java

@Deprecated
private String SignHeaders(String dataToSign, boolean isUser) throws NoSuchAlgorithmException,
        InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
        BadPaddingException, UnsupportedEncodingException, NoSuchProviderException, SignatureException {
    PKCS8EncodedKeySpec spec;/*  ww  w.ja v  a  2s.c o m*/
    if (isUser) {
        spec = new PKCS8EncodedKeySpec(
                Base64.decode(settings.getString(SETTINGS_USER_PRIVATE_KEY, "").getBytes(), 0));
    } else {
        spec = new PKCS8EncodedKeySpec(
                Base64.decode(settings.getString(SETTINGS_PROBE_PRIVATE_KEY, "").getBytes(), 0));
    }

    KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
    PrivateKey pk = kf.generatePrivate(spec);
    byte[] signed = null;

    //Log.e("algorithm", pk.getAlgorithm());

    Signature instance = Signature.getInstance("SHA1withRSA");
    instance.initSign(pk);
    instance.update(dataToSign.getBytes());
    signed = instance.sign();

    Log.e("privateKey", settings.getString(SETTINGS_USER_PRIVATE_KEY, ""));
    Log.e("privateKey", settings.getString(SETTINGS_PROBE_PRIVATE_KEY, ""));
    //Log.e("Signature",Base64.encodeToString(signed, Base64.NO_WRAP));

    return Base64.encodeToString(signed, Base64.NO_WRAP);
}

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

public void testHandleMessage() throws Exception {
    // setup//w  ww  .ja  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);

    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);
    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(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(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);

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

    // 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());
    assertEquals(userId, AuditTestService.getAuditUserId());
    assertEquals(userId, testHttpSession.getAttribute("eid.identifier"));
}

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

public void testHandleMessageWithoutAuditService() throws Exception {
    // setup/*from   www.j a va2  s. c  o 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);

    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(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.NRCID_SECRET_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(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(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)));
    EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);
    EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("1.2.3.4");

    // 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());
    assertNull(AuditTestService.getAuditUserId());
    assertEquals(userId, testHttpSession.getAttribute("eid.identifier"));
}