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: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.//from www  .ja v  a  2 s.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: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.//  www .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:com.sixsq.slipstream.cookie.CryptoUtils.java

/**
 * Determine if the given signature matches the given data.
 *
 * @param signed/*www  .ja  va  2 s .  c o m*/
 *            String representation of signature
 * @param data
 *            information to check
 *
 * @return true if the signature matches the given data, false otherwise
 */
public static boolean verify(String signed, String data) {

    boolean valid = false;

    try {

        Signature signature = Signature.getInstance(signatureAlgorithm);
        signature.initVerify(publicKey);

        signature.update(data.getBytes());

        byte[] signBytes = (new BigInteger(signed, radix)).toByteArray();
        valid = signature.verify(signBytes);

    } catch (NoSuchAlgorithmException e) {
        log.warning("Algorithm not recognized: " + signatureAlgorithm + " with details: " + e.getMessage());
    } catch (InvalidKeyException e) {
        log.warning(e.toString());
    } catch (SignatureException e) {
        log.warning(e.toString());
    }

    return valid;
}

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

/**
 * Sign the clear text content of DocContentSecurity and return a DocumentSignatute
 * @param doc/*from   ww  w .  ja  va 2s  .  c om*/
 * @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.turo.pushy.apns.AuthenticationToken.java

public boolean verifySignature(final ApnsVerificationKey verificationKey)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    if (!this.header.getKeyId().equals(verificationKey.getKeyId())) {
        return false;
    }//from  w w w  . j a  va 2s .c  om

    if (!this.claims.getIssuer().equals(verificationKey.getTeamId())) {
        return false;
    }

    final byte[] headerAndClaimsBytes;

    final String headerJson = GSON.toJson(this.header);
    final String claimsJson = GSON.toJson(this.claims);

    final StringBuilder headerAndClaimsBuilder = new StringBuilder();

    headerAndClaimsBuilder
            .append(Base64.encodeBase64URLSafeString(headerJson.getBytes(StandardCharsets.US_ASCII)));
    headerAndClaimsBuilder.append('.');
    headerAndClaimsBuilder
            .append(Base64.encodeBase64URLSafeString(claimsJson.getBytes(StandardCharsets.US_ASCII)));

    headerAndClaimsBytes = headerAndClaimsBuilder.toString().getBytes(StandardCharsets.US_ASCII);

    final Signature signature = Signature.getInstance(ApnsKey.APNS_SIGNATURE_ALGORITHM);
    signature.initVerify(verificationKey);
    signature.update(headerAndClaimsBytes);

    return signature.verify(this.signatureBytes);
}

From source file:com.vmware.identity.samlservice.SamlServiceTest.java

@Test
public void testVerifySignatureVcd() throws Exception {
    // pick a sample VCD message
    String message = "SAMLResponse=fZJNb9swDIb%2FiqF7LPnbEeIUw4oCAVoMqN"
            + "MedhlomU49yJJrSml%2F%2FuykX8uhFwGkXpKvHmpz9Tro4IgT9dZULAoF"
            + "C9Ao2%2FbmULGH%2Fc2qZFfbDcGg41He2oP17h5ptIYwmEsNyfNdxfxkpA"
            + "XqSRoYkKRTsv5xdyvjUMhxss4qq1lwjeR6A%2B407sm5kSTnkQijtAgzES"
            + "apTNOEK219y%2B104IpGvkzg9exI49kBB90D8aNqWbC7rtifrmkhVaop26h"
            + "oijJLEOajXBdtl2KSZ7PMvNve24pBmkG%2BLiBumr%2BJyNZJLqKuzRC7J"
            + "4RmZrAj8rgz5MC4isUiilciW8XRPo5klktRhlGZ%2FmbB4zu5%2BZXsjZM"
            + "8FU9f8XxPB4hwWoiw7UJkBqJ7419XAGMeNqg1Hj2Gx%2BEFJgyVHWQhSsF"
            + "fsCGyfOkS87r%2BtaDa8K8OPvZWO3CeLsKftsXgEbTH793RSS1rrxQSMX7"
            + "R5m5OwgG39%2Fjs590GdNZ1Xr%2BZuRRepD%2Fj%2F3%2FX9h8%3D&SigA"
            + "lg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rs" + "a-sha256";

    // sign using our algorithm
    SignatureAlgorithm algo = SignatureAlgorithm.getSignatureAlgorithmForURI(TestConstants.SIGNATURE_ALGORITHM);
    Signature sig = Signature.getInstance(algo.getAlgorithmName());
    sig.initSign(privateKey);/*from   w w  w  . j  a  va 2  s  .com*/

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

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

    // verify signature here
    sig.initVerify(x509Certificate.getPublicKey());
    sig.update(messageBytes);
    boolean verifies = sig.verify(sigBytes);
    log.debug("signature verifies in test: " + verifies);

    // just call verifySignature method and expect to not throw
    service.verifySignature(message, signature);
    /* disabled now: task 1301740
    // import our csp settings
    CasIdmClient idmClient = new CasIdmClient(SharedUtils.getIdmHostName());
            
    SharedUtils.importConfiguration(idmClient, VSPHERE_LOCAL_TENANT,
        "/csp.xml");
            
    CasIdmAccessor idmAccessor = new CasIdmAccessor(idmClient);
    log.debug("CSP settings imported successfully");
    idmAccessor.setTenant(VSPHERE_LOCAL_TENANT);
            
    // create new SamlService
    SamlServiceFactory factory2 = new DefaultSamlServiceFactory();
    CertificateFactory certFactory = CertificateFactory
        .getInstance("X.509");
    CertPath certPath = certFactory.generateCertPath(idmAccessor
        .getSAMLAuthorityChain());
    SamlService service2 = factory2.createSamlService(
        idmClient.getTenantPrivateKey(VSPHERE_LOCAL_TENANT),
        SignatureAlgorithm.RSA_SHA256, SignatureAlgorithm.RSA_SHA256,
        idmClient.getEntityID(VSPHERE_LOCAL_TENANT), certPath);
            
    // now call it again with generated signature
    String vcdSignature = "YkgxdGRqY3FiVlQvUWRLTWRHUjF1V2dJeGJZa0pHNTJJ" +
        "NGd0RUsyUEtZTDAzcloyNWJ3dmxuLzg3TlNMN1JsSVhYc2NOSkxTaVZ4Mm" +
        "c4TjNxWTBTLzg2Z0dvYjZVdVU5elY2cEZtQnJ2N0ZFZFdndFJwVDlvZE5w" +
        "VVpaa3BxQ1ROZVU4STRQYTltMVVOTDB1TUp5ckJvaVBnY3dUbk5LTko4S0" +
        "dxMWNLMlVuWTZBZGlodW5XaXdTZW5CVDVVRjZ6MHFHWmZ2d25kM2dkTWl4" +
        "eHY2WWovVElXWUg5REZYN2FJN3R0a3RTaSs5dUhTbUViMTFWRElNcGhpbm" +
        "1rdldGT3VWWHIxWFR5RUNKYnpLNXhYR3ArZXZ1UGk2TzR1UDlEVjlVdjlU" +
        "V01uVVNPYkw1aExEUDFadC9Vbzl0S1MySWIwcUp0OGIzVzV2UzVDWVdlUU" +
        "JGRTBnPT0%3D";
    vcdSignature = URLDecoder.decode(vcdSignature, "UTF-8");
    vcdSignature = Shared.decodeString(vcdSignature);
    // just call verifySignature method and expect to not throw
            
    service2.verifySignature(message, vcdSignature);*/
}

From source file:com.znsx.util.licence.LicenceUtil.java

/**
 * ???/*from   www . j  a  v a  2  s .c  o  m*/
 * 
 * @param data
 *            ??
 * @param publicKey
 *            2
 * @param signature
 *            base64????
 * @return
 * @throws Exception
 * @author huangbuji
 *         <p />
 *         Create at 2014-2-12 ?5:37:18
 */
public static boolean verifyBinKey(String data, byte[] publicKey, String signature) throws Exception {
    Base64 base64 = new Base64();
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
    PublicKey pub = KeyFactory.getInstance("DSA").generatePublic(keySpec);
    // ?
    Signature sign = Signature.getInstance("DSA");
    sign.initVerify(pub);
    sign.update(data.getBytes("utf8"));
    // return sign.verify(decoder.decodeBuffer(signature));
    return sign.verify(base64.decode(signature.getBytes("utf8")));
}

From source file:org.esupportail.papercut.services.PayBoxService.java

public boolean checkPayboxSignature(String queryString, String signature) {

    String sData = queryString.substring(0, queryString.lastIndexOf("&"));

    try {//from  www.j  a v  a  2s .c  o  m
        Signature sig = Signature.getInstance("SHA1WithRSA");
        byte[] sigBytes = Base64.decodeBase64(signature.getBytes());
        sig.initVerify(payboxPublicKey);
        sig.update(sData.getBytes());
        boolean signatureOk = sig.verify(sigBytes);
        if (!signatureOk) {
            log.error("Erreur lors de la vrification de la signature, les donnes ne correspondent pas.");
            log.error(sData);
            log.error(signature);
        }
        return signatureOk;
    } catch (Exception e) {
        log.warn("Pb when checking SSL signature of Paybox", e);
        return false;
    }
}

From source file:org.apache.xml.security.algorithms.implementations.SignatureECDSA.java

/**
 * Constructor SignatureRSA/*from ww  w .j  a  va 2 s  .  c  om*/
 *
 * @throws XMLSignatureException
 */
public SignatureECDSA() throws XMLSignatureException {

    String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());

    if (log.isDebugEnabled()) {
        log.debug("Created SignatureECDSA using " + algorithmID);
    }
    String provider = JCEMapper.getProviderId();
    try {
        if (provider == null) {
            this.signatureAlgorithm = Signature.getInstance(algorithmID);
        } else {
            this.signatureAlgorithm = Signature.getInstance(algorithmID, provider);
        }
    } catch (java.security.NoSuchAlgorithmException ex) {
        Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };

        throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
    } catch (NoSuchProviderException ex) {
        Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };

        throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
    }
}

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

/**
 * Integration test for automatic recovery of a {@link PrivateKey} instance.
 * <p/>//from   www  .  j ava  2  s  . com
 * 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));
}