Example usage for java.security Signature getInstance

List of usage examples for java.security Signature getInstance

Introduction

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

Prototype

public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Signature object that implements the specified signature algorithm.

Usage

From source file:test.integ.be.fedict.hsm.client.HSMProxyClientTest.java

@Test
public void testSign() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);//from w ww .  jav  a  2s  .  c o  m
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    String location = "http://localhost:8080/hsm-proxy-ws/dss";
    // String location = "https://www.e-contract.be/hsm-proxy-ws/dss";
    HSMProxyClient client = new HSMProxyClient(location, authnPrivateKey, authnCert);
    // client.setProxy("proxy.yourict.net", 8080);

    byte[] toBeSigned = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    messageDigest.update(toBeSigned);
    byte[] digestValue = messageDigest.digest();

    String keyAlias = "alias";

    byte[] signatureValue = client.sign(digestValue, "SHA1", keyAlias);
    assertNotNull(signatureValue);
    LOG.debug("signature value length: " + signatureValue.length);

    X509Certificate certificate = client.getCertificateChain(keyAlias).get(0);
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(certificate.getPublicKey());
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:test.be.fedict.eid.applet.PcscTest.java

@Test
public void pcscAuthnSignature() throws Exception {
    this.messages = new Messages(Locale.GERMAN);
    PcscEid pcscEid = new PcscEid(new TestView(), this.messages);
    if (false == pcscEid.isEidPresent()) {
        LOG.debug("insert eID card");
        pcscEid.waitForEidPresent();/* w w  w.  j  a  v  a  2s.  c o  m*/
    }
    byte[] challenge = "hello world".getBytes();
    byte[] signatureValue;
    List<X509Certificate> authnCertChain;
    try {
        // pcscEid.logoff();
        // pcscEid.selectBelpicJavaCardApplet();
        signatureValue = pcscEid.signAuthn(challenge);

        long t0 = System.currentTimeMillis();
        pcscEid.signAuthn(challenge);
        long t1 = System.currentTimeMillis();
        LOG.debug("dt: " + (t1 - t0));

        authnCertChain = pcscEid.getAuthnCertificateChain();
        LOG.debug("key size: " + authnCertChain.get(0).getPublicKey().getEncoded().length * 8);
        // pcscEid.logoff();
    } finally {
        pcscEid.close();
    }

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(authnCertChain.get(0).getPublicKey());
    signature.update(challenge);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);
    LOG.debug("sha1 hex: " + DigestUtils.shaHex(authnCertChain.get(0).getPublicKey().getEncoded()));
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.VirtualFirealarmSecurityManager.java

public static String signMessage(String encryptedData, PrivateKey signatureKey)
        throws VirtualFirealarmDeviceMgtPluginException {

    Signature signature;/*from w w  w .  jav a2 s  .c  o m*/
    String signedEncodedString;

    try {
        signature = Signature.getInstance(SHA_512);
        signature.initSign(signatureKey);
        signature.update(Base64.decodeBase64(encryptedData));

        byte[] signatureBytes = signature.sign();
        signedEncodedString = Base64.encodeBase64String(signatureBytes);

    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm not found exception occurred for Signature instance of [" + SHA_512 + "]";
        log.error(errorMsg);
        throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature exception occurred for Signature instance of [" + SHA_512 + "]";
        log.error(errorMsg);
        throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e);
    } catch (InvalidKeyException e) {
        String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + signatureKey + "\n]\n";
        log.error(errorMsg);
        throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e);
    }

    return signedEncodedString;
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFirealarmSecurityManager.java

public static String signMessage(String encryptedData, PrivateKey signatureKey)
        throws VirtualFirealarmDeviceMgtPluginException {

    Signature signature;/*from  w  w w . j a  v a  2 s  .  c  om*/
    String signedEncodedString;

    try {
        signature = Signature.getInstance(SIGNATURE_ALG);
        signature.initSign(signatureKey);
        signature.update(Base64.decodeBase64(encryptedData));

        byte[] signatureBytes = signature.sign();
        signedEncodedString = Base64.encodeBase64String(signatureBytes);

    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm not found exception occurred for Signature instance of [" + SIGNATURE_ALG
                + "]";
        log.error(errorMsg);
        throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature exception occurred for Signature instance of [" + SIGNATURE_ALG + "]";
        log.error(errorMsg);
        throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e);
    } catch (InvalidKeyException e) {
        String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + signatureKey + "\n]\n";
        log.error(errorMsg);
        throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e);
    }

    return signedEncodedString;
}

From source file:de.thorstenberger.examServer.pdf.signature.SignPdf.java

/**
 * Add a signature and a cryptographic timestamp to a pdf document. See www.ietf.org/rfc/rfc3161.txt. Proves that this
 * pdf had the current content at the current point in time.
 *
 * @param originalPdf/*from   w ww .  ja  v  a 2 s  .c om*/
 * @param targetPdf
 * @param pk
 * @param certChain
 * @param revoked
 * @param tsaAddress
 *          address of a rfc 3161 compatible timestamp server
 * @param reason
 *          reason for the signature
 * @param location
 *          location of signing
 * @param contact
 *          emailaddress of the person who is signing
 * @throws IOException
 * @throws DocumentException
 * @throws SignatureException
 */
public static void signAndTimestamp(final InputStream originalPdf, final OutputStream targetPdf,
        final PrivateKey pk, final X509Certificate[] certChain, final CRL[] revoked, final String tsaAddress,
        final String reason, final String location, final String contact)
        throws IOException, DocumentException, SignatureException {
    // only an estimate, depends on the certificates returned by the TSA
    final int timestampSize = 4400;
    Security.addProvider(new BouncyCastleProvider());

    final PdfReader reader = new PdfReader(originalPdf);
    final PdfStamper stamper = PdfStamper.createSignature(reader, targetPdf, '\0');
    final PdfSignatureAppearance sap = stamper.getSignatureAppearance();

    // comment next lines to have an invisible signature
    sap.setVisibleSignature(new Rectangle(450, 650, 500, 700), 1, null);
    sap.setLayer2Text("");

    final PdfSigGenericPKCS sig = new PdfSigGenericPKCS.PPKMS("BC");
    final HashMap<PdfName, Integer> exclusionSizes = new HashMap<PdfName, Integer>();

    // some informational fields
    sig.setReason(reason);
    sig.setLocation(location);
    sig.setContact(contact);
    sig.setName(PdfPKCS7.getSubjectFields(certChain[0]).getField("CN"));
    sig.setDate(new PdfDate(Calendar.getInstance()));

    // signing stuff
    final byte[] digest = new byte[256];
    final byte[] rsaData = new byte[20];
    sig.setExternalDigest(digest, rsaData, "RSA");
    sig.setSignInfo(pk, certChain, revoked);
    final PdfString contents = (PdfString) sig.get(PdfName.CONTENTS);
    // *2 to get hex size, +2 for delimiters
    PdfLiteral contentsLit = new PdfLiteral((contents.toString().length() + timestampSize) * 2 + 2);
    exclusionSizes.put(PdfName.CONTENTS, new Integer(contentsLit.getPosLength()));
    sig.put(PdfName.CONTENTS, contentsLit);

    // certification; will display dialog or blue bar in Acrobat Reader

    sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);

    // process all the information set above
    sap.setCryptoDictionary(sig);
    sap.preClose(exclusionSizes);

    // calculate digest (hash)
    try {
        final MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        final byte[] buf = new byte[8192];
        int n;
        final InputStream inp = sap.getRangeStream();
        while ((n = inp.read(buf)) != -1) {
            messageDigest.update(buf, 0, n);
        }
        final byte[] hash = messageDigest.digest();

        // make signature (SHA1 the hash, prepend algorithm ID, pad, and encrypt with RSA)
        final Signature sign = Signature.getInstance("SHA1withRSA");
        sign.initSign(pk);
        sign.update(hash);
        final byte[] signature = sign.sign();

        // prepare the location of the signature in the target PDF
        contentsLit = (PdfLiteral) sig.get(PdfName.CONTENTS);
        final byte[] outc = new byte[(contentsLit.getPosLength() - 2) / 2];
        final PdfPKCS7 pkcs7 = sig.getSigner();
        pkcs7.setExternalDigest(signature, hash, "RSA");
        final PdfDictionary dic = new PdfDictionary();

        byte[] ssig = pkcs7.getEncodedPKCS7();
        try {
            // try to retrieve cryptographic timestamp from configured tsa server
            ssig = pkcs7.getEncodedPKCS7(null, null, new TSAClientBouncyCastle(tsaAddress), null);
        } catch (final RuntimeException e) {
            log.error("Could not retrieve timestamp from server.", e);
        }
        System.arraycopy(ssig, 0, outc, 0, ssig.length);

        // add the timestamped signature
        dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));

        // finish up
        sap.close(dic);
    } catch (final InvalidKeyException e) {
        throw new RuntimeException("Internal implementation error! No such signature type.", e);
    } catch (final NoSuchAlgorithmException e) {
        throw new RuntimeException("Internal implementation error! No such algorithm type.", e);
    }
}

From source file:mx.com.quadrum.service.util.firma.ValidacionesCertificado.java

/**
 * Mtodo que valida el password y que la llave privada corresponda a la
 * llave publica//from w  w w. j  a v  a2 s  .c o  m
 *
 * @return true si el password y llave privada corresponden, en otro caso
 * false
 */
public boolean validaCorrespondencias() {

    try {

        PKCS8Key pkcs8 = new PKCS8Key(this.clavePrivada, this.password.toCharArray());
        //valida el pass
        PrivateKey pk = pkcs8.getPrivateKey();
        //valida que la llave privada corresponda  a la llave publica
        X509Certificate cert = X509Certificate.getInstance(this.clavePublica);
        Signature firma = Signature.getInstance("SHA1withRSA");
        firma.initSign(pk);
        byte[] firmado = firma.sign();
        firma.initVerify(cert.getPublicKey());
        if (firma.verify(firmado)) {
            return this.correcto;
        } else {
            return this.error;
        }
    } catch (GeneralSecurityException e) {

        return this.error;
    } catch (CertificateException e) {

        return this.error;
    }
}

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

private String signInternal(String plaintext, PrivateKey privateKey) throws Exception {
    Signature signature = Signature.getInstance(signatureAlgorithm);
    signature.initSign(privateKey);//from  w w  w  .  j a  va  2s . co m
    signature.update(plaintext.getBytes());

    return new String(Base64.encodeBase64(signature.sign()));
}

From source file:org.apli.modelbeans.facturacion.cfdi.CFDv32.java

@Override
public void verificar() throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory
            .createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER, new ByteArrayInputStream(cbs)).getKey();

    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(cert);//from w w w . j a v a  2 s. c  o  m
    sig.update(bytes);
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature");
    }
}

From source file:com.eucalyptus.blockstorage.HttpTransfer.java

/**
 * Calculates and sets the Authorization header value for the request using the EucaRSA-V2 signing algorithm
 * Algorithm Overview:/*w w  w.j a v  a  2s. c  om*/
 * 
 * 1. Generate the canonical Request
 *  a.) CanonicalRequest =
 *          HTTPRequestMethod + '\n' +
 *          CanonicalURI + '\n' +
 *          CanonicalQueryString + '\n' +
 *          CanonicalHeaders + '\n' +
 *          SignedHeaders
 *    b.) Where CanonicalURI = 
 *    c.) Where CanonicalQueryString = 
 *   d.) Where CanonicalHeaders =  sorted (by lowercased header name) ';' delimited list of <lowercase(headername)>:<value> items
 *   e.) Where SignedHeaders = sorted, ';' delimited list of headers in CanonicalHeaders
 * 
 * 2. Signature = RSA(privkey, SHA256(CanonicalRequest))
 * 
 * 3. Add an Authorization HTTP header to the request that contains the following strings, separated by spaces:
 * EUCA2-RSA-SHA256
 * The lower-case hexadecimal encoding of the component's X.509 certificate's md5 fingerprint
 * The SignedHeaders list calculated in Task 1
 * The Base64 encoding of the Signature calculated in Task 2
 * 
 * @param httpBaseRequest -- the request, the 'Authorization' header will be added to the request
 */
public static void signEucaInternal(HttpMethodBase httpBaseRequest) {
    StringBuilder canonicalRequest = new StringBuilder();
    String canonicalURI = null;
    String verb = httpBaseRequest.getName();
    canonicalURI = httpBaseRequest.getPath();

    String canonicalQuery = calcCanonicalQuery(httpBaseRequest);
    String[] processedHeaders = getCanonicalAndSignedHeaders(httpBaseRequest);
    String canonicalHeaders = processedHeaders[0];
    String signedHeaders = processedHeaders[1];

    canonicalRequest.append(verb).append('\n');
    canonicalRequest.append(canonicalURI).append('\n');
    canonicalRequest.append(canonicalQuery).append('\n');
    canonicalRequest.append(canonicalHeaders).append('\n');
    canonicalRequest.append(signedHeaders);

    StringBuilder authHeader = new StringBuilder(EUCA2_AUTH_ID);
    String signature = null;
    String fingerprint = null;
    try {
        Credentials ccCreds = SystemCredentials.lookup(Storage.class);
        PrivateKey ccPrivateKey = ccCreds.getPrivateKey();
        fingerprint = ccCreds.getCertFingerprint();
        Signature sign = Signature.getInstance("SHA256withRSA");
        sign.initSign(ccPrivateKey);
        LOG.debug("Signing canonical request: " + canonicalRequest.toString());
        sign.update(canonicalRequest.toString().getBytes());
        byte[] sig = sign.sign();
        signature = new String(Base64.encode(sig));
    } catch (Exception ex) {
        LOG.error("Signing error while signing request", ex);
    }

    authHeader.append(" ").append(fingerprint.toLowerCase()).append(" ").append(signedHeaders.toString())
            .append(" ").append(signature);
    httpBaseRequest.addRequestHeader(EUCA2_AUTH_HEADER_NAME, authHeader.toString());
}

From source file:net.sf.keystore_explorer.crypto.signing.MidletSigner.java

private static byte[] signJarDigest(File jarFile, RSAPrivateKey privateKey) throws CryptoException {
    // Create a SHA-1 signature for the supplied JAR file

    FileInputStream fis = null;/*from   w w  w.  ja v  a2s .c  o m*/

    try {
        Signature signature = Signature.getInstance(SignatureType.SHA1_RSA.jce());

        signature.initSign(privateKey);
        fis = new FileInputStream(jarFile);

        byte buffer[] = new byte[1024];
        int read = 0;

        while ((read = fis.read(buffer)) != -1) {
            signature.update(buffer, 0, read);
        }

        return signature.sign();
    } catch (IOException ex) {
        throw new CryptoException(res.getString("JarDigestSignatureFailed.exception.message"), ex);
    } catch (GeneralSecurityException ex) {
        throw new CryptoException(res.getString("JarDigestSignatureFailed.exception.message"), ex);
    } finally {
        IOUtils.closeQuietly(fis);
    }
}