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.SignatureDataMessageHandlerTest.java

@Test
public void testHandleMessageInvalidSignature() throws Exception {
    // setup/*  w  w w. j av  a 2  s .c om*/
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", 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("AuditService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("AuditServiceClass"))
            .andStubReturn(AuditTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter("SignatureService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("SignatureServiceClass"))
            .andStubReturn(SignatureTestService.class.getName());

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

    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    byte[] document = "hello world".getBytes();
    byte[] digestValue = messageDigest.digest(document);
    EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_VALUE_SESSION_ATTRIBUTE))
            .andStubReturn(digestValue);
    EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_ALGO_SESSION_ATTRIBUTE))
            .andStubReturn("SHA-1");

    SignatureDataMessage message = new SignatureDataMessage();
    message.certificateChain = new LinkedList<X509Certificate>();
    message.certificateChain.add(certificate);

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(keyPair.getPrivate());
    signature.update("foobar-document".getBytes());
    byte[] signatureValue = signature.sign();
    message.signatureValue = signatureValue;

    // 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(SignatureTestService.getSignatureValue());
        assertEquals("remote-address", AuditTestService.getAuditSignatureRemoteAddress());
        assertEquals(certificate, AuditTestService.getAuditSignatureClientCertificate());
    }
}

From source file:com.mycompany.bankinterface.crypto.Signer.java

public String sign(String clearText) throws SignerException {
    Signature dsa;

    try {/*from w  w w. ja  va  2 s . co m*/
        dsa = Signature.getInstance(SIGNER_ALGORITHM, PROVIDER);
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SignerException("Could not get signing instance", ex);
    }

    try {
        dsa.initSign(keyPair.getPrivate());
        dsa.update(clearText.getBytes());

        byte[] signature = dsa.sign();
        String signatureAsString = Base64.encodeBase64String(signature);
        return signatureAsString;

    } catch (InvalidKeyException | SignatureException ex) {
        throw new SignerException("Failed to initialise signing algorithm", ex);
    }
}

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

public void testHandleMessagePSS_SHA256() throws Exception {
    // setup/* w  w  w  .  j a  va  2 s. c o  m*/
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", 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("AuditService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("AuditServiceClass")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("SignatureService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("SignatureServiceClass"))
            .andStubReturn(SignatureTestService.class.getName());

    MessageDigest messageDigest = MessageDigest.getInstance("SHA256");
    byte[] document = "hello world".getBytes();
    byte[] digestValue = messageDigest.digest(document);
    EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_VALUE_SESSION_ATTRIBUTE))
            .andStubReturn(digestValue);
    EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_ALGO_SESSION_ATTRIBUTE))
            .andStubReturn("SHA-256-PSS");

    SignatureDataMessage message = new SignatureDataMessage();
    message.certificateChain = new LinkedList<X509Certificate>();
    message.certificateChain.add(certificate);

    Signature signature = Signature.getInstance("SHA256withRSA/PSS", "BC");
    signature.initSign(keyPair.getPrivate());
    signature.update(document);
    byte[] signatureValue = signature.sign();
    message.signatureValue = signatureValue;

    // 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(signatureValue, SignatureTestService.getSignatureValue());
}

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

protected static void checkCmpResponseGeneral(byte[] retMsg, String issuerDN, X500Name userDN,
        Certificate cacert, byte[] senderNonce, byte[] transId, boolean signed, String pbeSecret,
        String expectedSignAlg)/*from  www  . j ava 2s  . c o  m*/
        throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    assertNotNull("No response from server.", retMsg);
    assertTrue("Response was of 0 length.", retMsg.length > 0);
    boolean pbe = (pbeSecret != null);
    //
    // Parse response message
    //
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg));
    PKIMessage respObject = null;
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    // The signer, i.e. the CA, check it's the right CA
    PKIHeader header = respObject.getHeader();

    // Check that the message is signed with the correct digest alg
    if (StringUtils.isEmpty(expectedSignAlg)) {
        expectedSignAlg = PKCSObjectIdentifiers.sha1WithRSAEncryption.getId();
    }
    // if cacert is ECDSA we should expect an ECDSA signature alg
    //if (AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECDSA")) {
    //    expectedSignAlg = X9ObjectIdentifiers.ecdsa_with_SHA1.getId();
    //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECGOST3410")) {
    //    expectedSignAlg = CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001.getId();
    //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("DSTU4145")) {
    //    expectedSignAlg = (new ASN1ObjectIdentifier(CesecoreConfiguration.getOidDstu4145())).getId();
    //}
    if (signed) {
        AlgorithmIdentifier algId = header.getProtectionAlg();
        assertNotNull(
                "Protection algorithm was null when expecting a signed response, this was propably an unprotected error message: "
                        + header.getFreeText(),
                algId);
        assertEquals(expectedSignAlg, algId.getAlgorithm().getId());
    }
    if (pbe) {
        AlgorithmIdentifier algId = header.getProtectionAlg();
        assertNotNull(
                "Protection algorithm was null when expecting a pbe protected response, this was propably an unprotected error message: "
                        + header.getFreeText(),
                algId);
        assertEquals("Protection algorithm id: " + algId.getAlgorithm().getId(),
                CMPObjectIdentifiers.passwordBasedMac.getId(), algId.getAlgorithm().getId()); // 1.2.840.113549.1.1.5 - SHA-1 with RSA Encryption
    }

    // Check that the signer is the expected CA    
    assertEquals(header.getSender().getTagNo(), 4);

    X500Name expissuer = new X500Name(issuerDN);
    X500Name actissuer = new X500Name(header.getSender().getName().toString());
    assertEquals(expissuer, actissuer);
    if (signed) {
        // Verify the signature
        byte[] protBytes = CmpMessageHelper.getProtectedBytes(respObject);
        DERBitString bs = respObject.getProtection();
        Signature sig;
        try {
            sig = Signature.getInstance(expectedSignAlg, "BC");
            sig.initVerify(cacert);
            sig.update(protBytes);
            boolean ret = sig.verify(bs.getBytes());
            assertTrue(ret);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (SignatureException e) {
            e.printStackTrace();
            assertTrue(false);
        }
    }
    if (pbe) {
        ASN1OctetString os = header.getSenderKID();
        assertNotNull(os);
        String keyId = CmpMessageHelper.getStringFromOctets(os);
        log.debug("Found a sender keyId: " + keyId);
        // Verify the PasswordBased protection of the message
        byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(respObject);
        DERBitString protection = respObject.getProtection();
        AlgorithmIdentifier pAlg = header.getProtectionAlg();
        log.debug("Protection type is: " + pAlg.getAlgorithm().getId());
        PBMParameter pp = PBMParameter.getInstance(pAlg.getParameters());
        int iterationCount = pp.getIterationCount().getPositiveValue().intValue();
        log.debug("Iteration count is: " + iterationCount);
        AlgorithmIdentifier owfAlg = pp.getOwf();
        // Normal OWF alg is 1.3.14.3.2.26 - SHA1
        log.debug("Owf type is: " + owfAlg.getAlgorithm().getId());
        AlgorithmIdentifier macAlg = pp.getMac();
        // Normal mac alg is 1.3.6.1.5.5.8.1.2 - HMAC/SHA1
        log.debug("Mac type is: " + macAlg.getAlgorithm().getId());
        byte[] salt = pp.getSalt().getOctets();
        // log.info("Salt is: "+new String(salt));
        byte[] raSecret = pbeSecret != null ? pbeSecret.getBytes() : new byte[0];
        byte[] basekey = new byte[raSecret.length + salt.length];
        System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
        for (int i = 0; i < salt.length; i++) {
            basekey[raSecret.length + i] = salt[i];
        }
        // Construct the base key according to rfc4210, section 5.1.3.1
        MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(),
                BouncyCastleProvider.PROVIDER_NAME);
        for (int i = 0; i < iterationCount; i++) {
            basekey = dig.digest(basekey);
            dig.reset();
        }
        // HMAC/SHA1 os normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7
        String macOid = macAlg.getAlgorithm().getId();
        Mac mac = Mac.getInstance(macOid, BouncyCastleProvider.PROVIDER_NAME);
        SecretKey key = new SecretKeySpec(basekey, macOid);
        mac.init(key);
        mac.reset();
        mac.update(protectedBytes, 0, protectedBytes.length);
        byte[] out = mac.doFinal();
        // My out should now be the same as the protection bits
        byte[] pb = protection.getBytes();
        boolean ret = Arrays.equals(out, pb);
        assertTrue(ret);
    }

    // --SenderNonce
    // SenderNonce is something the server came up with, but it should be 16
    // chars
    byte[] nonce = header.getSenderNonce().getOctets();
    assertEquals(nonce.length, 16);

    // --Recipient Nonce
    // recipient nonce should be the same as we sent away as sender nonce
    nonce = header.getRecipNonce().getOctets();
    assertEquals(new String(nonce), new String(senderNonce));

    // --Transaction ID
    // transid should be the same as the one we sent
    nonce = header.getTransactionID().getOctets();
    assertEquals(new String(nonce), new String(transId));

}

From source file:org.ejbca.ui.cmpclient.commands.KeyUpdateRequestCommand.java

@Override
public PKIMessage generatePKIMessage(ParameterContainer parameters) throws Exception {
    boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY));
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));
    boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY);

    if (verbose) {
        log.info("Creating KeyUpdate request with: SubjectDN=" + userDN.toString());
        log.info("Creating KeyUpdate request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating KeyUpdate request with: IncludePopo=" + includePopo);
    }/*from w w w  .ja  v a 2  s.  co m*/

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

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    myCertTemplate.setValidity(myOptionalValidity);

    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }

    myCertTemplate.setSubject(userDN);

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

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

        DERBitString bs = new DERBitString(sig.sign());

        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    } else {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    }

    // myCertReqMsg.addRegInfo(new AttributeTypeAndValue(new
    // ASN1ObjectIdentifier("1.3.6.2.2.2.2.3.1"), new
    // DERInteger(1122334455)));
    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(""));
    AttributeTypeAndValue[] avs = { av };

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

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(null);

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    return myPKIMessage;
}

From source file:architecture.common.license.validator.CheckSignatureValidator.java

public void validate(License license) throws LicenseException {
    try {/* www  .  j  av a 2  s  .co  m*/
        //   DSA ? .
        String publicKey = "308201b83082012c06072a8648ce3804013082011f02818100fd7f53811d75122952df4a9c2eece4e7f611b7523cef4400c31e3f80b6512669455d402251fb593d8d58fabfc5f5ba30f6cb9b556cd7813b801d346ff26660b76b9950a5a49f9fe8047b1022c24fbba9d7feb7c61bf83b57e7c6a8a6150f04fb83f6d3c51ec3023554135a169132f675f3ae2b61d72aeff22203199dd14801c70215009760508f15230bccb292b982a2eb840bf0581cf502818100f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa3aea82f9574c0b3d0782675159578ebad4594fe67107108180b449167123e84c281613b7cf09328cc8a6e13c167a8b547c8d28e0a3ae1e2bb3a675916ea37f0bfa213562f1fb627a01243bcca4f1bea8519089a883dfe15ae59f06928b665e807b552564014c3bfecf492a0381850002818100faf2d25b2866aa68501094d1097bebc95c6bcf1c58766f18b35fbf5e9d761cc5bf913447e374c21d279777859f9f043d1dc0d58b93a2081b56b4f5269a81b076907a3b11b01ec5cfde5dae4dfd7d26346e53e611235e714e69ec1bc141c77a8a28c4c799df570a4c3240e7f2fee19d6ed4caaa1b15b5da4a967ee82e3eb4d4ca";

        byte pub[] = Hex.decodeHex(publicKey.toCharArray());
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pub);

        KeyFactory keyFactory = KeyFactory.getInstance("DSA");
        java.security.PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
        Signature sig = Signature.getInstance("DSA");

        sig.initVerify(pubKey);
        // license.getSignature().getBytes("UTF-8");
        byte decoded[] = Hex.decodeHex(license.getSignature().toCharArray());

        log.debug("decoded sig: " + Hex.encodeHexString(decoded));

        log.info((new StringBuilder()).append("Validating license. License fingerprint: ")
                .append(license.getSignature()).toString());

        sig.update(license.getFingerprint());

        boolean verified = sig.verify(decoded);

        if (!verified)
            throw new LicenseException("License signature is invalid.");
    } catch (Exception e) {
        log.fatal(e.getMessage(), e);
        throw new LicenseException(e);
    }
}

From source file:com.mycompany.bankinterface.crypto.Signer.java

public boolean isVerified(String clearText, String signature, String signerPublicKey) throws SignerException {

    boolean isVerified = false;

    byte[] signerPublicKeyBytes = Base64.decodeBase64(signerPublicKey);
    byte[] signatureAsBytes = Base64.decodeBase64(signature);

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(signerPublicKeyBytes);
    KeyFactory keyFactory;/* w  w w  .  j a v  a 2s  . c o m*/

    try {
        keyFactory = KeyFactory.getInstance(PUBLIC_KEY_ALGORITHM, PROVIDER);
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SignerException("Failed to create key factory", ex);
    }

    PublicKey pubKey;

    try {
        pubKey = keyFactory.generatePublic(pubKeySpec);
    } catch (InvalidKeySpecException ex) {
        throw new SignerException("Failed to create public key", ex);
    }

    Signature dsa;

    try {
        dsa = Signature.getInstance(SIGNER_ALGORITHM, PROVIDER);
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SignerException("Could not get signing instance", ex);
    }

    try {
        dsa.initVerify(pubKey);
        dsa.update(clearText.getBytes());
        isVerified = dsa.verify(signatureAsBytes);

    } catch (InvalidKeyException | SignatureException ex) {
        throw new SignerException("Could not verify data", ex);
    }

    return isVerified;
}

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

/**
 * Sign the clear text content of DocContentSecurity and return a DocumentSignatute
 * @param doc//from   w  ww .j a  va2s  .  c o  m
 * @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:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * Returns the string formatted digital signature for the data.
 * /* w w w.j  av a2s.  c  o m*/
 * @param key
 *            Private key for signing the data.
 * @param data
 *            Data for which the signature is to be generated.
 * @return signed data with the provide private key.
 * @throws NoSuchAlgorithmException
 *             if the specified algorithm is not available.
 * @throws InvalidKeyException
 *             if privateKey is not valid.
 * @throws SignatureException
 *             if this Signature instance is not initialized properly.
 */
private String getDataSig(PrivateKey key, String data)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {

    // Generate Signature For the data
    Signature signature = Signature.getInstance("SHA256withRSA");
    signature.initSign(key);
    signature.update(data.getBytes());
    byte[] sigBytes = signature.sign();
    return Base64.encodeToString(sigBytes, Base64.DEFAULT);
}

From source file:com.axelor.apps.account.service.payment.PayboxService.java

/**
 * verification signature RSA des donnees avec cle publique
 * @param dataBytes//from   w ww.  j a  v a2  s  .  c  om
 * @param sigBytes
 * @param pubKey
 * @return
 * @throws Exception
 */
private boolean verify(byte[] dataBytes, byte[] sigBytes, String sigAlg, PublicKey pubKey) throws Exception {
    Signature signature = Signature.getInstance(sigAlg);
    signature.initVerify(pubKey);
    signature.update(dataBytes);
    return signature.verify(sigBytes);
}