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.jrummyapps.busybox.utils.ZipSigner.java

/**
 * Tool to sign JAR files (including APKs and OTA updates) in a way compatible with the mincrypt verifier, using
 * SHA1 and RSA keys.//  w w  w .j av a2 s.  c  om
 *
 * @param unsignedZip
 *     The path to the APK, ZIP, JAR to sign
 * @param destination
 *     The output file
 * @return true if successfully signed the file
 */
public static boolean signZip(File unsignedZip, File destination) {
    final AssetManager am = App.getContext().getAssets();
    JarArchiveOutputStream outputJar = null;
    JarFile inputJar = null;

    try {
        X509Certificate publicKey = readPublicKey(am.open(PUBLIC_KEY));
        PrivateKey privateKey = readPrivateKey(am.open(PRIVATE_KEY));

        // Assume the certificate is valid for at least an hour.
        long timestamp = publicKey.getNotBefore().getTime() + 3600L * 1000;

        inputJar = new JarFile(unsignedZip, false); // Don't verify.
        FileOutputStream stream = new FileOutputStream(destination);
        outputJar = new JarArchiveOutputStream(stream);
        outputJar.setLevel(9);

        // MANIFEST.MF
        Manifest manifest = addDigestsToManifest(inputJar);
        JarArchiveEntry je = new JarArchiveEntry(JarFile.MANIFEST_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);
        manifest.write(outputJar);

        ZipSignature signature1 = new ZipSignature();
        signature1.initSign(privateKey);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writeSignatureFile(manifest, out);

        // CERT.SF
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKey);
        je = new JarArchiveEntry(CERT_SF_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);
        byte[] sfBytes = writeSignatureFile(manifest, new SignatureOutputStream(outputJar, signature));

        signature1.update(sfBytes);
        byte[] signatureBytes = signature1.sign();

        // CERT.RSA
        je = new JarArchiveEntry(CERT_RSA_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);

        outputJar.write(readContentAsBytes(am.open(TEST_KEY)));
        outputJar.write(signatureBytes);

        copyFiles(manifest, inputJar, outputJar, timestamp);
    } catch (Exception e) {
        Crashlytics.logException(e);
        return false;
    } finally {
        IoUtils.closeQuietly(inputJar);
        IoUtils.closeQuietly(outputJar);
    }
    return true;
}

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/**
 * Tool to sign JAR files (including APKs and OTA updates) in a way compatible with the mincrypt verifier, using
 * SHA1 and RSA keys.//w  w w  . j av a2s  .c  o  m
 *
 * @param unsignedZip
 *     The path to the APK, ZIP, JAR to sign
 * @param destination
 *     The output file
 * @return true if successfully signed the file
 */
public static boolean signZip(File unsignedZip, File destination) {
    final AssetManager am = App.getContext().getAssets();
    JarArchiveOutputStream outputJar = null;
    JarFile inputJar = null;

    try {
        X509Certificate publicKey = readPublicKey(am.open(PUBLIC_KEY));
        PrivateKey privateKey = readPrivateKey(am.open(PRIVATE_KEY));

        // Assume the certificate is valid for at least an hour.
        long timestamp = publicKey.getNotBefore().getTime() + 3600L * 1000;

        inputJar = new JarFile(unsignedZip, false); // Don't verify.
        FileOutputStream stream = new FileOutputStream(destination);
        outputJar = new JarArchiveOutputStream(stream);
        outputJar.setLevel(9);

        // MANIFEST.MF
        Manifest manifest = addDigestsToManifest(inputJar);
        JarArchiveEntry je = new JarArchiveEntry(JarFile.MANIFEST_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);
        manifest.write(outputJar);

        ZipSignature signature1 = new ZipSignature();
        signature1.initSign(privateKey);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writeSignatureFile(manifest, out);

        // CERT.SF
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKey);
        je = new JarArchiveEntry(CERT_SF_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);
        byte[] sfBytes = writeSignatureFile(manifest, new SignatureOutputStream(outputJar, signature));

        signature1.update(sfBytes);
        byte[] signatureBytes = signature1.sign();

        // CERT.RSA
        je = new JarArchiveEntry(CERT_RSA_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);

        outputJar.write(readContentAsBytes(am.open(TEST_KEY)));
        outputJar.write(signatureBytes);

        copyFiles(manifest, inputJar, outputJar, timestamp);
    } catch (Exception e) {
        Crashlytics.logException(e);
        return false;
    } finally {
        IOUtils.closeQuietly(inputJar);
        IOUtils.closeQuietly(outputJar);
    }
    return true;
}

From source file:org.signserver.module.mrtdsodsigner.MRTDSODSigner.java

static byte[] getSampleSignedData(byte[] dataToBeSigned, PrivateKey privateKey)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    byte[] encryptedDigest = null;

    Signature s = null;
    s = Signature.getInstance("SHA256withRSA");
    s.initSign(privateKey);
    s.update(dataToBeSigned);//from  w ww. j  a  v  a  2s. c  om
    encryptedDigest = s.sign();
    return encryptedDigest;
}

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

public static PKIMessage buildCertBasedPKIProtection(PKIMessage pKIMessage, CMPCertificate[] extraCerts,
        PrivateKey key, String digestAlg, String provider) throws NoSuchProviderException,
        NoSuchAlgorithmException, SecurityException, SignatureException, InvalidKeyException {
    // Select which signature algorithm we should use for the response, based on the digest algorithm and key type.
    ASN1ObjectIdentifier oid = AlgorithmTools.getSignAlgOidFromDigestAndKey(digestAlg, key.getAlgorithm());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Selected signature alg oid: " + oid.getId() + ", key algorithm: " + key.getAlgorithm());
    }/*from   w ww.jav a 2  s. co  m*/
    // According to PKCS#1 AlgorithmIdentifier for RSA-PKCS#1 has null Parameters, this means a DER Null (asn.1 encoding of null), not Java null.
    // For the RSA signature algorithms specified above RFC3447 states "...the parameters MUST be present and MUST be NULL."
    PKIHeaderBuilder headerBuilder = getHeaderBuilder(pKIMessage.getHeader());
    AlgorithmIdentifier pAlg = null;
    if ("RSA".equalsIgnoreCase(key.getAlgorithm())) {
        pAlg = new AlgorithmIdentifier(oid, DERNull.INSTANCE);
    } else {
        pAlg = new AlgorithmIdentifier(oid);
    }
    headerBuilder.setProtectionAlg(pAlg);
    // Most PKCS#11 providers don't like to be fed an OID as signature algorithm, so 
    // we use BC classes to translate it into a signature algorithm name instead
    PKIHeader head = headerBuilder.build();
    String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Signing CMP message with signature alg: " + signatureAlgorithmName);
    }
    Signature sig = Signature.getInstance(signatureAlgorithmName, provider);
    sig.initSign(key);
    sig.update(CmpMessageHelper.getProtectedBytes(head, pKIMessage.getBody()));

    if ((extraCerts != null) && (extraCerts.length > 0)) {
        pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign()), extraCerts);
    } else {
        pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign()));
    }
    return pKIMessage;
}

From source file:com.netscape.cms.servlet.test.DRMTest.java

/**
 * Verify the generated asymmetric key pair.
 *
 * @param keyAlgorithm - Algorithm used to generate keys.
 * @param privateKey - binary data of the private key.
 * @param publicKey - binary data of he public key.
 * @return//  ww  w  .j a  va  2 s  .  co m
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws IOException
 */
public static boolean isKeyPairValid(String keyAlgorithm, byte[] privateKey, byte[] publicKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException,
        IOException {
    String algorithm = keyAlgorithm.toUpperCase();
    String signingAlgorithm = "SHA1with" + algorithm;
    KeyFactory factory = KeyFactory.getInstance(algorithm);
    PrivateKey priKey = factory.generatePrivate(new PKCS8EncodedKeySpec(privateKey));
    PublicKey pubKey = factory.generatePublic(new X509EncodedKeySpec(publicKey));
    Signature sig = Signature.getInstance(signingAlgorithm);
    sig.initSign(priKey);
    String s = "Data to test asymmetric keys.";
    sig.update(s.getBytes());

    // Sign the data with the private key.
    byte[] realSig = sig.sign();

    Signature sig2 = Signature.getInstance(signingAlgorithm);
    sig2.initVerify(pubKey);

    sig2.update(s.getBytes());
    // Verify the signature with the public key.
    return sig2.verify(realSig);
}

From source file:com.vmware.identity.SharedUtils.java

/**
 * Produce a string with signature/* w ww  .  ja va2  s. c  o m*/
 *
 * @param privateKey
 * @param relayStateParameter
 * @param samlRequestParameter
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws SignatureException
 */
public static String getSamlRequestSignature(PrivateKey privateKey, String relayStateParameter,
        String samlRequestParameter)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, SignatureException {
    // produce signature
    SignatureAlgorithm algo = SignatureAlgorithm.getSignatureAlgorithmForURI(TestConstants.SIGNATURE_ALGORITHM);
    Signature sig = Signature.getInstance(algo.getAlgorithmName());
    sig.initSign(privateKey);

    String messageToSign = Shared.SAML_REQUEST_PARAMETER + "="
            + URLEncoder.encode(samlRequestParameter, "UTF-8") + "&" + Shared.RELAY_STATE_PARAMETER + "="
            + URLEncoder.encode(relayStateParameter, "UTF-8") + "&" + Shared.SIGNATURE_ALGORITHM_PARAMETER + "="
            + URLEncoder.encode(algo.toString(), "UTF-8");

    byte[] messageBytes = messageToSign.getBytes();
    sig.update(messageBytes);

    byte[] sigBytes = sig.sign();
    String signature = Shared.encodeBytes(sigBytes);
    return signature;
}

From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java

/**
 * Creates a test signature and verifies it.
 *
 * @param privateKey Private key to sign with
 * @param publicKey Public key to verify with
 * @param signatureProvider Name of provider to sign with
 * @throws NoSuchAlgorithmException In case the key or signature algorithm is unknown
 * @throws NoSuchProviderException In case the supplied provider name is unknown or BC is not installed
 * @throws InvalidKeyException If signature verification failed or the key was invalid
 * @throws SignatureException If the signature could not be made or verified correctly
 *//*ww  w .j  a  v a 2  s .co  m*/
public static void testSignAndVerify(PrivateKey privateKey, PublicKey publicKey, String signatureProvider)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
    final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes();
    final String sigAlg = suggestSigAlg(publicKey);
    if (sigAlg == null) {
        throw new NoSuchAlgorithmException("Unknown key algorithm: " + publicKey.getAlgorithm());
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Testing keys with algorithm: " + publicKey.getAlgorithm());
        LOG.debug("testSigAlg: " + sigAlg);
        LOG.debug("provider: " + signatureProvider);
        LOG.trace("privateKey: " + privateKey);
        LOG.trace("privateKey class: " + privateKey.getClass().getName());
        LOG.trace("publicKey: " + publicKey);
        LOG.trace("publicKey class: " + publicKey.getClass().getName());
    }
    final Signature signSignature = Signature.getInstance(sigAlg, signatureProvider);
    signSignature.initSign(privateKey);
    signSignature.update(input);
    byte[] signBA = signSignature.sign();
    if (LOG.isTraceEnabled()) {
        LOG.trace("Created signature of size: " + signBA.length);
        LOG.trace("Created signature: " + new String(Hex.encode(signBA)));
    }

    final Signature verifySignature = Signature.getInstance(sigAlg, "BC");
    verifySignature.initVerify(publicKey);
    verifySignature.update(input);
    if (!verifySignature.verify(signBA)) {
        throw new InvalidKeyException("Test signature inconsistent");
    }
}

From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java

/**
 * Returns the signature text for the byte array of data
 * // ww w.j av a2  s. c  o m
 * @param signer
 *            The algorithm to sign with
 * @param privateKey
 *            The private key to sign with
 * @param data
 *            The data to be signed
 * @return The signature text
 */
public static String sign(Signature signer, PrivateKey privateKey, byte[] data) {
    String signature;

    try {
        signer.initSign(privateKey);
        signer.update(data);

        byte[] sigBytes = signer.sign();

        signature = (new String(Base64.encodeBase64URLSafe(sigBytes))).replace("=", "");

    } catch (GeneralSecurityException generalSecurityException) {

        // generalSecurityException.printStackTrace();

        throw new IllegalStateException(generalSecurityException);

    }

    return signature;
}

From source file:Manifest.java

/**
 * This method creates a manifest file with the specified name, for the
 * specified vector of files, using the named message digest algorithm. If
 * signername is non-null, it adds a digital signature to the manifest,
 * using the named signature algorithm. This method can throw a bunch of
 * exceptions.//from  ww  w.j  a v a  2s. c  o  m
 */
public static void create(String manifestfile, String digestAlgorithm, String signername,
        String signatureAlgorithm, KeyStore keystore, String password, List filelist)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, KeyStoreException,
        UnrecoverableKeyException, IOException {
    // For computing a signature, we have to process the files in a fixed,
    // repeatable order, so sort them alphabetically.
    Collections.sort(filelist);
    int numfiles = filelist.size();

    Properties manifest = new Properties(), metadata = new Properties();
    MessageDigest md = MessageDigest.getInstance(digestAlgorithm);
    Signature signature = null;
    byte[] digest;

    // If a signer name was specified, then prepare to sign the manifest
    if (signername != null) {
        // Get a Signature object
        signature = Signature.getInstance(signatureAlgorithm);

        // Look up the private key of the signer from the keystore
        PrivateKey key = (PrivateKey) keystore.getKey(signername, password.toCharArray());

        // No prepare to create a signature for the specified signer
        signature.initSign(key);
    }

    // Now, loop through the files, in a well-known alphabetical order
    System.out.print("Computing message digests");
    for (int i = 0; i < numfiles; i++) {
        String filename = (String) filelist.get(i);
        // Compute the digest for each, and skip files that don't exist.
        try {
            digest = getFileDigest(filename, md);
        } catch (IOException e) {
            System.err.println("\nSkipping " + filename + ": " + e);
            continue;
        }
        // If we're computing a signature, use the bytes of the filename
        // and of the digest as part of the data to sign.
        if (signature != null) {
            signature.update(filename.getBytes());
            signature.update(digest);
        }
        // Store the filename and the encoded digest bytes in the manifest
        manifest.put(filename, hexEncode(digest));
        System.out.print('.');
        System.out.flush();
    }

    // If a signer was specified, compute signature for the manifest
    byte[] signaturebytes = null;
    if (signature != null) {
        System.out.print("done\nComputing digital signature...");
        System.out.flush();

        // Compute the digital signature by encrypting a message digest of
        // all the bytes passed to the update() method using the private
        // key of the signer. This is a time consuming operation.
        signaturebytes = signature.sign();
    }

    // Tell the user what comes next
    System.out.print("done\nWriting manifest...");
    System.out.flush();

    // Store some metadata about this manifest, including the name of the
    // message digest algorithm it uses
    metadata.put("__META.DIGESTALGORITHM", digestAlgorithm);
    // If we're signing the manifest, store some more metadata
    if (signername != null) {
        // Store the name of the signer
        metadata.put("__META.SIGNER", signername);
        // Store the name of the algorithm
        metadata.put("__META.SIGNATUREALGORITHM", signatureAlgorithm);
        // And generate the signature, encode it, and store it
        metadata.put("__META.SIGNATURE", hexEncode(signaturebytes));
    }

    // Now, save the manifest data and the metadata to the manifest file
    FileOutputStream f = new FileOutputStream(manifestfile);
    manifest.store(f, "Manifest message digests");
    metadata.store(f, "Manifest metadata");
    System.out.println("done");
}

From source file:jef.tools.security.EncrypterUtil.java

/**
 * DSA??//from   w  w  w . j a v a2  s.  c  om
 * 
 * @param in
 * @return
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws SignatureException
 */
public static byte[] getDSASign(InputStream in, PrivateKey key) {
    try {
        java.security.Signature signet = java.security.Signature.getInstance("DSA");
        signet.initSign(key);
        byte[] b = new byte[1024];
        int len;
        while ((len = in.read(b)) != -1) {
            signet.update(b, 0, len);
        }
        byte[] signed = signet.sign();
        return signed;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}