Example usage for java.security Signature initSign

List of usage examples for java.security Signature initSign

Introduction

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

Prototype

public final void initSign(PrivateKey privateKey) throws InvalidKeyException 

Source Link

Document

Initialize this object for signing.

Usage

From source file:com.aqnote.shared.cryptology.asymmetric.DSA.java

/**
 * ???//from w  w w . j a  v  a  2 s.co m
 * 
 * @param content ????
 * @param keyPairName key pair
 * @return base64???
 */
public String sign(byte[] content, String keyPairName) throws RuntimeException {
    KeyPairEntry entry = (KeyPairEntry) keyPairs.get(keyPairName);
    if (entry == null || entry.privateKey == null) {
        return null;
    }

    try {
        Signature signature = Signature.getInstance(ALGORITHM);
        signature.initSign(entry.privateKey);
        signature.update((byte[]) content);
        byte[] signed = signature.sign();

        if (log.isDebugEnabled()) {
            log.debug("Java signature[length=" + signed.length + "]: " + toHexString(signed));
        }

        return Base64.encodeBase64String(signed);
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.sshtools.j2ssh.transport.publickey.dsa.SshDssPrivateKey.java

/**
 *
 *
 * @param data//from  www.ja  v  a 2s. co  m
 *
 * @return
 *
 * @throws InvalidSshKeySignatureException
 */
public byte[] generateSignature(byte[] data) throws InvalidSshKeySignatureException {
    try {

        Signature sig = Signature.getInstance("SHA1withDSA");
        sig.initSign(prvkey);

        /*java.util.Random rnd = new java.util.Random();
           byte[] buffer = new byte[20];
           rnd.nextBytes(buffer);
           sig.update(buffer);
           byte[] test = sig.sign();*/
        sig.update(data);

        byte[] signature = sig.sign();
        byte[] decoded = new byte[40];

        SimpleASNReader asn = new SimpleASNReader(signature);
        asn.getByte();
        asn.getLength();
        asn.getByte();

        byte[] r = asn.getData();

        asn.getByte();

        byte[] s = asn.getData();

        if (r.length >= 20) {
            System.arraycopy(r, r.length - 20, decoded, 0, 20);
        } else {
            System.arraycopy(r, 0, decoded, 20 - r.length, r.length);
        }

        if (s.length >= 20) {
            System.arraycopy(s, s.length - 20, decoded, 20, 20);
        } else {
            System.arraycopy(s, 0, decoded, 20 + (20 - s.length), s.length);
        }

        if (log.isDebugEnabled()) {

            BigInteger rb = new BigInteger(1, r);
            log.debug(rb.toString(16));

            BigInteger sb = new BigInteger(1, s);
            log.debug(sb.toString(16));

            log.debug("s length is " + String.valueOf(s.length));
            log.debug("r length is " + String.valueOf(r.length));

            String str = "";

            for (int i = 0; i < signature.length; i++) {
                str += (Integer.toHexString(signature[i] & 0xFF) + " ");
            }

            log.debug("Java signature is " + str);

            str = "";

            for (int i = 0; i < decoded.length; i++) {
                str += (Integer.toHexString(decoded[i] & 0xFF) + " ");
            }

            log.debug("SSH signature is " + str);
        }

        ByteArrayWriter baw = new ByteArrayWriter();
        baw.writeString(getAlgorithmName());
        baw.writeBinaryString(decoded);

        return baw.toByteArray();
    } catch (Exception e) {
        throw new InvalidSshKeySignatureException(e);
    }
}

From source file:net.sf.dsig.query.QuerystringStrategy.java

@Override
public String signPlaintext(String plaintext, PrivateKey privateKey, X509Certificate[] certificateChain)
        throws Exception {
    Signature signature = Signature.getInstance(signatureAlgorithm);
    signature.initSign(privateKey);
    signature.update(plaintext.getBytes());

    String signatureAsBase64 = signInternal(plaintext, privateKey);

    String serialNumberAsString = serialNumberInHexadecimal
            ? HexStringHelper.toHexString(certificateChain[0].getSerialNumber().toByteArray())
            : "" + certificateChain[0].getSerialNumber();

    return "{ \"signature\": \"" + signatureAsBase64 + "\", \"serialNumber\": \"" + serialNumberAsString
            + "\" }";
}

From source file:com.streamsets.datacollector.publicrestapi.TestCredentialsDeploymentResource.java

@Test
public void testSuccess() throws Exception {
    Properties sdcProps = new Properties();
    sdcProps.setProperty("a", "b");
    sdcProps.setProperty("c", "d");
    sdcProps.setProperty("kerberos.client.keytab", "sdc.keytab");
    sdcProps.setProperty("kerberos.client.enabled", "false");
    sdcProps.setProperty("kerberos.client.principal", "sdc/_HOST@EXAMPLE.COM");
    File sdcFile = new File(RuntimeInfoTestInjector.confDir, "sdc.properties");

    Properties dpmProps = new Properties();
    dpmProps.setProperty("x", "y");
    dpmProps.setProperty("z", "a");
    dpmProps.setProperty("dpm.enabled", "false");
    dpmProps.setProperty("dpm.base.url", "http://localhost:18631");
    File dpmFile = new File(RuntimeInfoTestInjector.confDir, "dpm.properties");

    try (FileWriter fw = new FileWriter(sdcFile)) {
        sdcProps.store(fw, "");
    }//from w ww . j  av  a2s.  co  m

    try (FileWriter fw = new FileWriter(dpmFile)) {
        dpmProps.store(fw, "");
    }

    Response response = null;
    KeyPair keys = generateKeys();
    mockCheckForCredentialsRequiredToTrue();
    System.setProperty(DPM_AGENT_PUBLIC_KEY, Base64.getEncoder().encodeToString(keys.getPublic().getEncoded()));
    String token = "Frenchies and Pandas";
    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initSign(keys.getPrivate());
    sig.update(token.getBytes(Charsets.UTF_8));
    List<String> labels = Arrays.asList("deployment-prod-1", "deployment-prod-2");
    CredentialsBeanJson json = new CredentialsBeanJson(token, "streamsets/172.1.1.0@EXAMPLE.COM",
            Base64.getEncoder().encodeToString("testKeytab".getBytes(Charsets.UTF_8)),
            Base64.getEncoder().encodeToString(sig.sign()), "https://dpm.streamsets.com:18631",
            Arrays.asList("deployment-prod-1", "deployment-prod-2"), "deployment1:org");

    try {
        response = target("/v1/deployment/deployCredentials").request().post(Entity.json(json));
        Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
        CredentialDeploymentResponseJson responseJson = OBJECT_MAPPER
                .readValue((InputStream) response.getEntity(), CredentialDeploymentResponseJson.class);
        Assert.assertEquals(CredentialDeploymentStatus.CREDENTIAL_USED_AND_DEPLOYED,
                responseJson.getCredentialDeploymentStatus());

        // Verify sdc.properties
        sdcProps = new Properties();
        try (FileReader fr = new FileReader(sdcFile)) {
            sdcProps.load(fr);
        }
        Assert.assertEquals("b", sdcProps.getProperty("a"));
        Assert.assertEquals("d", sdcProps.getProperty("c"));
        Assert.assertEquals("streamsets/172.1.1.0@EXAMPLE.COM",
                sdcProps.getProperty("kerberos.client.principal"));
        Assert.assertEquals("true", sdcProps.getProperty("kerberos.client.enabled"));
        Assert.assertEquals("sdc.keytab", sdcProps.getProperty("kerberos.client.keytab"));
        byte[] keyTab = Files.toByteArray(new File(RuntimeInfoTestInjector.confDir, "sdc.keytab"));
        Assert.assertEquals("testKeytab", new String(keyTab, Charsets.UTF_8));
        response = target("/v1/definitions").request().get();
        Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

        dpmProps = new Properties();
        try (FileReader fr = new FileReader(dpmFile)) {
            dpmProps.load(fr);
        }
        Assert.assertEquals("y", dpmProps.getProperty("x"));
        Assert.assertEquals("a", dpmProps.getProperty("z"));
        Assert.assertEquals("true", dpmProps.getProperty("dpm.enabled"));
        Assert.assertEquals(
                Configuration.FileRef.PREFIX + "application-token.txt" + Configuration.FileRef.SUFFIX,
                dpmProps.getProperty("dpm.appAuthToken"));
        Assert.assertEquals("https://dpm.streamsets.com:18631", dpmProps.getProperty("dpm.base.url"));

        Assert.assertEquals(StringUtils.join(labels.toArray(), ","),
                dpmProps.getProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS));
        Assert.assertEquals("deployment1:org", dpmProps.getProperty(RemoteSSOService.DPM_DEPLOYMENT_ID));

        File tokenFile = new File(RuntimeInfoTestInjector.confDir, "application-token.txt");
        try (FileInputStream fr = new FileInputStream(tokenFile)) {
            int len = token.length();
            byte[] tokenBytes = new byte[len];
            Assert.assertEquals(len, fr.read(tokenBytes));
            Assert.assertEquals(token, new String(tokenBytes, Charsets.UTF_8));
        }
        //Test redeploying the credentials again
        response = target("/v1/deployment/deployCredentials").request().post(Entity.json(json));
        responseJson = OBJECT_MAPPER.readValue((InputStream) response.getEntity(),
                CredentialDeploymentResponseJson.class);
        Assert.assertEquals(CredentialDeploymentStatus.CREDENTIAL_NOT_USED_ALREADY_DEPLOYED,
                responseJson.getCredentialDeploymentStatus());

    } finally {
        if (response != null) {
            response.close();
        }
    }
}

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

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

From source file:org.tolven.security.bean.DocProtectionBean.java

/**
 * Sign the clear text content of DocContentSecurity and return a DocumentSignatute
 * @param doc/*  w  w  w . j  a v  a 2s . com*/
 * @param activeAccountUser
 * @return
 */
public DocumentSignature sign(DocBase doc, AccountUser activeAccountUser, PrivateKey privateKey,
        X509Certificate x509Certificate) {
    if (doc.getContent() == null) {
        return null;
    }
    if (privateKey == null) {
        throw new RuntimeException("A private key is required to sign a document");
    }
    if (x509Certificate == null) {
        throw new RuntimeException("An X509 Certificate is required to sign a document");
    }
    String signatureAlgorithm = propertiesBean.getProperty(DocumentSignature.DOC_SIGNATURE_ALGORITHM_PROP);
    try {
        Signature signature = Signature.getInstance(signatureAlgorithm);
        signature.initSign(privateKey);
        byte[] document = getDecryptedContent(doc, activeAccountUser, privateKey);
        signature.update(document);
        DocumentSignature documentSignature = new DocumentSignature();
        documentSignature.setDocBase(doc);
        documentSignature.setSignature(signature.sign());
        documentSignature.setSignatureAlgorithm(signatureAlgorithm);
        documentSignature.setCertificate(x509Certificate.getEncoded());
        documentSignature.setUser(activeAccountUser.getUser());
        documentSignature.setTimstamp(new Date());
        em.persist(documentSignature);
        return documentSignature;
    } catch (Exception ex) {
        throw new RuntimeException("Could not sign documentId: " + doc.getId());
    }
}

From source file:nl.b3p.viewer.stripes.CycloramaActionBean.java

private byte[] sign(PrivateKey privateKey, String token)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {

    Signature instance = Signature.getInstance(SIG_ALGORITHM);
    instance.initSign(privateKey);
    instance.update(token.getBytes());//from www  . ja va 2 s. c  o m
    byte[] signature = instance.sign();

    return signature;
}

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

protected static PKIMessage genCertReq(String issuerDN, X500Name userDN, String altNames, KeyPair keys,
        Certificate cacert, byte[] nonce, byte[] transid, boolean raVerifiedPopo, Extensions extensions,
        Date notBefore, Date notAfter, BigInteger customCertSerno, AlgorithmIdentifier pAlg,
        DEROctetString senderKID) throws NoSuchAlgorithmException, NoSuchProviderException, IOException,
        InvalidKeyException, SignatureException {
    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    if (notBefore != null) {
        nb = new org.bouncycastle.asn1.x509.Time(notBefore);
    }//from www.  ja  v  a2s  .  c o  m
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    if (notAfter != null) {
        na = new org.bouncycastle.asn1.x509.Time(notAfter);
    }
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    if (issuerDN != null) {
        myCertTemplate.setIssuer(new X500Name(issuerDN));
    }
    myCertTemplate.setSubject(userDN);
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
    dIn.close();
    myCertTemplate.setPublicKey(keyInfo);
    // If we did not pass any extensions as parameter, we will create some of our own, standard ones
    Extensions exts = extensions;
    if (exts == null) {

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

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

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

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

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

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

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

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(
            new X500Name(issuerDN != null ? issuerDN : ((X509Certificate) cacert).getSubjectDN().getName())));

    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(pAlg);
    myPKIHeader.setSenderKID(senderKID);

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

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

public void testHandleMessageInvalidIntegritySignature() throws Exception {
    // setup//from w w w. j  av  a2  s  .c om
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(),
            "CN=TestNationalRegistration", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null,
            null);

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

    EasyMock.expect(mockServletConfig.getInitParameter("IdentityIntegrityService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("IdentityIntegrityServiceClass"))
            .andStubReturn(IdentityIntegrityTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter("AuditService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("AuditServiceClass"))
            .andStubReturn(AuditTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter("SkipNationalNumberCheck")).andStubReturn(null);

    EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("remote-address");

    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_ADDRESS_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_CERTIFICATES_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_PHOTO_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);

    byte[] idFile = "foobar-id-file".getBytes();
    IdentityDataMessage message = new IdentityDataMessage();
    message.idFile = idFile;

    KeyPair intruderKeyPair = MiscTestUtils.generateKeyPair();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(intruderKeyPair.getPrivate());
    signature.update(idFile);
    byte[] idFileSignature = signature.sign();
    message.identitySignatureFile = idFileSignature;
    message.rrnCertFile = certificate.getEncoded();

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

    // operate
    AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance);
    this.testedInstance.init(mockServletConfig);
    try {
        this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, mockHttpSession);
        fail();
    } catch (ServletException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // verify
        EasyMock.verify(mockServletConfig, mockHttpSession, mockServletRequest);
        assertNull(IdentityIntegrityTestService.getCertificate());
        assertEquals("remote-address", AuditTestService.getAuditIntegrityRemoteAddress());
    }
}

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

public void testHandleMessageWithIntegrityCheck() throws Exception {
    // setup//from w  ww.  jav a2  s  . c o m
    KeyPair rootKeyPair = MiscTestUtils.generateKeyPair();
    KeyPair rrnKeyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate rootCertificate = MiscTestUtils.generateCertificate(rootKeyPair.getPublic(),
            "CN=TestRootCA", notBefore, notAfter, null, rootKeyPair.getPrivate(), true, 0, null, null);
    X509Certificate rrnCertificate = MiscTestUtils.generateCertificate(rrnKeyPair.getPublic(),
            "CN=TestNationalRegistration", notBefore, notAfter, null, rootKeyPair.getPrivate(), false, 0, null,
            null);

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

    EasyMock.expect(mockServletConfig.getInitParameter("IdentityIntegrityService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("IdentityIntegrityServiceClass"))
            .andStubReturn(IdentityIntegrityTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter("AuditService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("AuditServiceClass")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("SkipNationalNumberCheck")).andStubReturn(null);

    EasyMock.expect(mockHttpSession.getAttribute("eid.identifier")).andStubReturn(null);

    mockHttpSession.setAttribute(EasyMock.eq("eid.identity"), EasyMock.isA(Identity.class));
    EasyMock.expect(mockHttpSession.getAttribute("eid")).andStubReturn(null);
    mockHttpSession.setAttribute(EasyMock.eq("eid"), EasyMock.isA(EIdData.class));

    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_ADDRESS_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_CERTIFICATES_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_PHOTO_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);

    byte[] idFile = "foobar-id-file".getBytes();
    IdentityDataMessage message = new IdentityDataMessage();
    message.idFile = idFile;

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(rrnKeyPair.getPrivate());
    signature.update(idFile);
    byte[] idFileSignature = signature.sign();
    message.identitySignatureFile = idFileSignature;
    message.rrnCertFile = rrnCertificate.getEncoded();
    message.rootCertFile = rootCertificate.getEncoded();

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

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

    // verify
    EasyMock.verify(mockServletConfig, mockHttpSession, mockServletRequest);
    assertEquals(rrnCertificate, IdentityIntegrityTestService.getCertificate());
}