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:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testPSS256() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//from   ww w.j a va 2 s .com
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PublicKey authnPublicKey = authnCertificate.getPublicKey();

    Signature signature = Signature.getInstance("SHA256withRSAandMGF1");
    signature.initSign(authnPrivateKey);

    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

private void verifySignatureAlgorithm(final String signatureAlgorithm, final PrivateKey privateKey,
        final PublicKey publicKey) throws Exception {
    Signature signature = Signature.getInstance(signatureAlgorithm);
    signature.initSign(privateKey);
    assertTrue(signature.getProvider() instanceof BeIDProvider);

    final byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);//from w  w w.j  av a  2 s .  co m
    final byte[] signatureValue = signature.sign();
    assertNotNull(signatureValue);

    signature.initVerify(publicKey);
    signature.update(toBeSigned);
    final boolean beIDResult = signature.verify(signatureValue);
    assertTrue(beIDResult);

    signature = Signature.getInstance(signatureAlgorithm);
    signature.initVerify(publicKey);
    signature.update(toBeSigned);
    final boolean result = signature.verify(signatureValue);
    assertTrue(result);

    RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(),
            rsaPublicKey.getModulus());
    LOG.debug("Padded DigestInfo: " + new String(Hex.encodeHex(messageBigInteger.toByteArray())));
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testPSSPrefix() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//w w w. j  a  v  a 2 s .c o m
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PublicKey authnPublicKey = authnCertificate.getPublicKey();

    Signature signature = Signature.getInstance("SHA1withRSAandMGF1");
    signature.initSign(authnPrivateKey);

    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);

    RSAPublicKey rsaPublicKey = (RSAPublicKey) authnPublicKey;
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(),
            rsaPublicKey.getModulus());
    String paddedMessage = new String(Hex.encodeHex(messageBigInteger.toByteArray()));
    LOG.debug("padded message: " + paddedMessage);
    assertTrue(paddedMessage.endsWith("bc"));
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

/**
 * Integration test for automatic recovery of a {@link PrivateKey} instance.
 * <p/>/* w  w  w .  j a v a2 s  .co  m*/
 * Automatic recovery should work on the same eID card.
 * <p/>
 * When inserting another eID card however, the automatic recovery should
 * fail.
 * 
 * @throws Exception
 */
@Test
public void testAutoRecovery() throws Exception {
    Security.addProvider(new BeIDProvider());

    KeyStore keyStore = KeyStore.getInstance("BeID");
    BeIDKeyStoreParameter keyStoreParameter = new BeIDKeyStoreParameter();
    keyStoreParameter.setAutoRecovery(true);
    keyStoreParameter.setCardReaderStickiness(true);
    keyStore.load(keyStoreParameter);

    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    PublicKey authnPublicKey = keyStore.getCertificate("Authentication").getPublicKey();
    final Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(authnPrivateKey);

    final byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));

    JOptionPane.showMessageDialog(null, "Please remove/insert eID card...");

    signature.initSign(authnPrivateKey);
    signature.update(toBeSigned);
    signatureValue = signature.sign();

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

private byte[] generateSignature(String tokenString) {

    byte[] signature = null;

    File ksFile = ConfigurationListener.getLterKeyStore();
    String ksType = ConfigurationListener.getLterKeyStoreType();
    String ksAlias = ConfigurationListener.getLterKeyStoreAlias();
    char[] storePass = ConfigurationListener.getLterStorePasswd().toCharArray();
    char[] keyPass = ConfigurationListener.getLterKeyPasswd().toCharArray();

    try {/*ww  w  .  ja v a  2  s. c o  m*/

        KeyStore ks = KeyStore.getInstance(ksType);
        FileInputStream ksFis = new FileInputStream(ksFile);
        BufferedInputStream ksBufIn = new BufferedInputStream(ksFis);

        ks.load(ksBufIn, storePass);
        PrivateKey priv = (PrivateKey) ks.getKey(ksAlias, keyPass);

        Signature rsa = Signature.getInstance("MD5withRSA");
        rsa.initSign(priv);

        rsa.update(tokenString.getBytes());
        signature = rsa.sign();

    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    return signature;

}

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

@Override
public PKIMessage generatePKIMessage(final ParameterContainer parameters) throws Exception {

    final boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY));
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));

    String authmodule = parameters.get(AUTHENTICATION_MODULE_KEY);
    String endentityPassword = "";
    if (authmodule != null && StringUtils.equals(authmodule, CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD)) {
        endentityPassword = parameters.containsKey(AUTHENTICATION_PARAM_KEY)
                ? parameters.get(AUTHENTICATION_PARAM_KEY)
                : "foo123";
    }//from w w w .j a va 2  s.c o m

    String altNames = parameters.get(ALTNAME_KEY);
    String serno = parameters.get(SERNO_KEY);
    BigInteger customCertSerno = null;
    if (serno != null) {
        customCertSerno = new BigInteger(serno, 16);
    }
    boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY);

    if (verbose) {
        log.info("Creating CRMF request with: SubjectDN=" + userDN.toString());
        log.info("Creating CRMF request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating CRMF request with: AuthenticationModule=" + authmodule);
        log.info("Creating CRMF request with: EndEntityPassword=" + endentityPassword);
        log.info("Creating CRMF request with: SubjectAltName=" + altNames);
        log.info("Creating CRMF request with: CustomCertSerno="
                + (customCertSerno == null ? "" : customCertSerno.toString(16)));
        log.info("Creating CRMF request with: IncludePopo=" + includePopo);
    }

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

    // We should be able to back date the start time when allow validity
    // override is enabled in the certificate profile
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_WEEK, -1);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    // in validity
    Date notBefore = cal.getTime();
    cal.add(Calendar.DAY_OF_WEEK, 3);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(notBefore);
    // in validity
    Date notAfter = cal.getTime();
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(notAfter);

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    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(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);

    // Create standard extensions
    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
    Extensions 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 (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, "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);
    } else {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    }

    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(endentityPassword));
    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);
    myPKIHeader.setSenderKID(new byte[0]);

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

    return myPKIMessage;
}

From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#signFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 *//*from  w w w  .  j  a  v  a2  s.  c o m*/
public synchronized FileSecurityResponse signFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#signFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            Signature signature = Signature.getInstance(fileSecurityConfig.getSignatureAlgorithm());
            signature.initSign(keyPair.getPrivate());
            signature.update(IOUtils.toByteArray(new FileInputStream(request.getUnsignedFile())));

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", signature);
            }

            byte[] sig = signature.sign();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
            }

            IOUtils.write(sig, new FileOutputStream(request.getSignedFile()));

            if ((request.getSignedFile().exists()) && (request.getSignedFile().length() != 0)) {
                response.setSignedFile(request.getSignedFile());
                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            } else {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);

        throw new FileSecurityException(fnfx.getMessage(), fnfx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (SignatureException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new FileSecurityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.SIGNFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:org.icestuff.getdown.maven.SignConfig.java

private void sign(File inputFile, File signatureFile)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, InvalidKeyException, SignatureException {
    // initialize the keystore
    KeyStore store = KeyStore.getInstance(storetype == null ? "JKS" : storetype);
    FileInputStream storeInput = new FileInputStream(getKeystore());
    store.load(storeInput, getStorepass().toCharArray());
    PrivateKey key = (PrivateKey) store.getKey(getAlias(),
            getKeypass() == null ? getKeypass().toCharArray() : getKeypass().toCharArray());

    // sign the digest file
    Signature sig = Signature.getInstance("SHA1withRSA");
    FileInputStream dataInput = new FileInputStream(inputFile);
    byte[] buffer = new byte[8192];
    int length;//from   w ww.j ava2s .c o m

    sig.initSign(key);
    while ((length = dataInput.read(buffer)) != -1) {
        sig.update(buffer, 0, length);
    }

    // Write out the signature
    FileOutputStream signatureOutput = new FileOutputStream(signatureFile);
    String signed = new String(Base64.encodeBase64(sig.sign()));
    signatureOutput.write(signed.getBytes("utf8"));
}

From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.AbstractXmlSignatureService.java

@SuppressWarnings("unchecked")
private byte[] getSignedXML(final String digestAlgo, final List<DigestInfo> digestInfos,
        final List<X509Certificate> signingCertificateChain, final PrivateKey signingKey)
        throws ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        MarshalException, javax.xml.crypto.dsig.XMLSignatureException, TransformerException, IOException,
        SAXException {//from  w  ww.  j a v  a2s  . com
    // DOM Document construction.
    Document document = getEnvelopingDocument();
    if (null == document) {
        final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        document = documentBuilderFactory.newDocumentBuilder().newDocument();
    }

    final XMLSignContext xmlSignContext = new DOMSignContext(signingKey, document);
    final URIDereferencer uriDereferencer = getURIDereferencer();
    if (null != uriDereferencer) {
        xmlSignContext.setURIDereferencer(uriDereferencer);
    }

    final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", //$NON-NLS-1$
            new org.jcp.xml.dsig.internal.dom.XMLDSigRI());

    // Add ds:References that come from signing client local files.
    final List<Reference> references = new LinkedList<Reference>();
    addDigestInfosAsReferences(digestInfos, signatureFactory, references);

    // Invoke the signature facets.
    final String signatureId = "xmldsig-" + UUID.randomUUID().toString(); //$NON-NLS-1$
    final List<XMLObject> objects = new LinkedList<XMLObject>();
    for (final SignatureFacet signatureFacet : this.signatureFacets) {
        signatureFacet.preSign(signatureFactory, document, signatureId, signingCertificateChain, references,
                objects);
    }

    // ds:SignedInfo
    final SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(getSignatureMethod(digestAlgo),
            null);
    final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod(
            getCanonicalizationMethod(), (C14NMethodParameterSpec) null), signatureMethod, references);

    // Creamos el KeyInfo
    final KeyInfoFactory kif = signatureFactory.getKeyInfoFactory();
    final List<Object> x509Content = new ArrayList<Object>();
    x509Content.add(signingCertificateChain.get(0));

    final List<Object> content = new ArrayList<Object>();
    try {
        content.add(kif.newKeyValue(signingCertificateChain.get(0).getPublicKey()));
    } catch (final Exception e) {
        Logger.getLogger("es.gob.afirma") //$NON-NLS-1$
                .severe("Error creando el KeyInfo, la informacion puede resultar incompleta: " + e); //$NON-NLS-1$
    }
    content.add(kif.newX509Data(x509Content));

    // JSR105 ds:Signature creation
    final String signatureValueId = signatureId + "-signature-value"; //$NON-NLS-1$
    final javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo,
            kif.newKeyInfo(content), // KeyInfo
            objects, signatureId, signatureValueId);

    // ds:Signature Marshalling.
    final DOMXMLSignature domXmlSignature = (DOMXMLSignature) xmlSignature;
    Node documentNode = document.getDocumentElement();
    if (null == documentNode) {
        documentNode = document; // In case of an empty DOM document.
    }
    final String dsPrefix = null;
    domXmlSignature.marshal(documentNode, dsPrefix, (DOMCryptoContext) xmlSignContext);

    // Completion of undigested ds:References in the ds:Manifests.
    for (final XMLObject object : objects) {

        final List<XMLStructure> objectContentList = object.getContent();
        for (final XMLStructure objectContent : objectContentList) {
            if (!(objectContent instanceof Manifest)) {
                continue;
            }
            final Manifest manifest = (Manifest) objectContent;
            final List<Reference> manifestReferences = manifest.getReferences();
            for (final Reference manifestReference : manifestReferences) {
                if (null != manifestReference.getDigestValue()) {
                    continue;
                }
                final DOMReference manifestDOMReference = (DOMReference) manifestReference;
                manifestDOMReference.digest(xmlSignContext);
            }
        }
    }

    // Completion of undigested ds:References.
    final List<Reference> signedInfoReferences = signedInfo.getReferences();
    for (final Reference signedInfoReference : signedInfoReferences) {
        final DOMReference domReference = (DOMReference) signedInfoReference;
        if (null != domReference.getDigestValue()) {
            // ds:Reference with external digest value
            continue;
        }
        domReference.digest(xmlSignContext);
    }

    // Calculation of signature
    final DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo;
    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
    domSignedInfo.canonicalize(xmlSignContext, dataStream);
    final byte[] octets = dataStream.toByteArray();
    final Signature sig = Signature.getInstance(digestAlgo.replace("-", "") + "withRSA"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    final byte[] sigBytes;
    try {
        sig.initSign(signingKey);
        sig.update(octets);
        sigBytes = sig.sign();
    } catch (final Exception e) {
        throw new javax.xml.crypto.dsig.XMLSignatureException(
                "Error en la firma PKCS#1 ('" + digestAlgo + "withRSA): " + e); //$NON-NLS-1$ //$NON-NLS-2$
    }

    // Sacamos el pre-XML a un OutputStream
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    writeDocument(document, baos);

    // Ya tenemos el XML, con la firma vacia y el SignatureValue, cada uno
    // por su lado...
    return postSign(baos.toByteArray(), signingCertificateChain, signatureId, sigBytes);

}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

/**
 * Verifies that the supplied private key and signed certificate match by signing/verifying some test data.
 * /*from   w ww .  j  ava  2 s.  c o m*/
 * @param privateKey A private key
 * @param cert the certificate
 * @throws ResourceException if the verification fails, or an error is encountered.
 */
protected void verify(PrivateKey privateKey, Certificate cert) throws ResourceException {
    PublicKey publicKey = cert.getPublicKey();
    byte[] data = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 };
    boolean verified;
    try {
        Signature signer = Signature.getInstance(privateKey.getAlgorithm());
        signer.initSign(privateKey);
        signer.update(data);
        byte[] signed = signer.sign();
        Signature verifier = Signature.getInstance(publicKey.getAlgorithm());
        verifier.initVerify(publicKey);
        verifier.update(data);
        verified = verifier.verify(signed);
    } catch (Exception e) {
        throw new InternalServerErrorException("Error verifying private key and signed certificate", e);
    }
    if (!verified) {
        throw new BadRequestException("Private key does not match signed certificate");
    }
}