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:Main.java

/**
 * Verify a signature of a stream.//from  w ww  .jav a 2  s. c o  m
 *
 * @param cert      The certificate containing the public key which will be used
 *                  to verify the signature.
 * @param signature The signature to verify.
 * @param stream    The stream to verify.
 * @return boolean true if the signature was valid otherwise false.
 */
public static boolean verifySignature(String algorithm, Certificate cert, byte[] signature, InputStream stream)
        throws InvalidKeyException, SignatureException, IOException {
    Signature sign;

    try {
        sign = Signature.getInstance(algorithm);
    } catch (NoSuchAlgorithmException badsigner) {
        throw new IOException("Could not initialize signer with algorithm " + algorithm);
    }

    sign.initVerify(cert);

    byte[] buffer = new byte[1024];

    while (true) {
        int read = stream.read(buffer);

        if (read < 0) {
            break;
        }

        sign.update(buffer, 0, read);
    }

    return sign.verify(signature);
}

From source file:aiai.ai.utils.checksum.ChecksumWithSignatureService.java

public static boolean isValid(byte[] data, String signatureAsBase64, PublicKey publicKey) {
    try {//from  w  ww .j  a  va2s  .co  m
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initVerify(publicKey);
        signature.update(data);
        //noinspection UnnecessaryLocalVariable
        final byte[] bytes = Base64.decodeBase64(signatureAsBase64);
        boolean status = signature.verify(bytes);
        return status;
    } catch (GeneralSecurityException e) {
        log.error("Error checking signature", e);
        throw new RuntimeException("Error", e);
    }
}

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

/**
 * Constructor SignatureDSA//  w ww.  ja  va  2  s. c  om
 *
 * @throws XMLSignatureException
 */
public SignatureDSA() throws XMLSignatureException {
    String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA.URI);
    if (log.isDebugEnabled()) {
        log.debug("Created SignatureDSA 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 (java.security.NoSuchProviderException ex) {
        Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
        throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
    }
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.certificate.DefaultJSONSigner.java

private byte[] signCsrData(String csrJSONData, PrivateKey privateKey)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Signature signature = Signature.getInstance("SHA256withRSA");
    signature.initSign(privateKey);/*from   w w w  .ja va 2 s .  co  m*/
    signature.update(csrJSONData.getBytes());
    return signature.sign();
}

From source file:test.integ.be.fedict.hsm.PKCS11Test.java

@Test
public void testEToken() throws Exception {
    File tmpConfigFile = File.createTempFile("pkcs11-", ".conf");
    tmpConfigFile.deleteOnExit();//  w  w w .  j a v a2 s . co m
    PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile));
    configWriter.println("name=test");
    configWriter.println("library=/usr/lib/libeTPkcs11.so");
    configWriter.println("slotListIndex=0");
    configWriter.close();
    SunPKCS11 sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(sunPKCS11);

    Security.removeProvider(sunPKCS11.getName());
    sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(sunPKCS11);

    Security.removeProvider(sunPKCS11.getName());
    sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(sunPKCS11);

    Security.removeProvider(sunPKCS11.getName());
    sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(sunPKCS11);

    Security.removeProvider(sunPKCS11.getName());
    sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(sunPKCS11);

    KeyStore keyStore = KeyStore.getInstance("PKCS11", sunPKCS11);
    keyStore.load(null, "HSMProxy1234".toCharArray());
    Enumeration<String> aliasesEnum = keyStore.aliases();
    String alias = aliasesEnum.nextElement();

    PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, "HSMProxy1234".toCharArray());

    final int TEST_COUNT = 50;
    int count = TEST_COUNT;
    while (count > 0) {
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKey);
        signature.update("to be signed".getBytes());
        signature.sign();
        count--;
    }
}

From source file:org.gluu.oxpush2.u2f.v2.cert.KeyPairGeneratorImpl.java

@Override
public byte[] sign(byte[] signedData, PrivateKey privateKey) throws U2FException {
    try {/*from  w w w . j ava 2s.c o m*/
        Signature signature = Signature.getInstance("SHA256withECDSA");
        signature.initSign(privateKey);
        signature.update(signedData);
        return signature.sign();
    } catch (NoSuchAlgorithmException ex) {
        throw new U2FException("Error when signing", ex);
    } catch (SignatureException ex) {
        throw new U2FException("Error when signing", ex);
    } catch (InvalidKeyException ex) {
        throw new U2FException("Error when signing", ex);
    }
}

From source file:com.zxy.commons.codec.rsa.RSAUtils.java

/**
 * <p>//  ww w . ja  v a 2 s .co  m
 * ?????
 * </p>
 * 
 * @param data ?
 * @param privateKey ?(BASE64?)
 * 
 * @return String
 * @throws Exception Exception
 */
public static String sign(byte[] data, String privateKey) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(privateK);
    signature.update(data);
    return new String(Base64.encodeBase64(signature.sign()));
}

From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java

/**
 * Verifies the certificate authenticity using the configured TrustStore and the signature of
 * the speechlet request.//from  www  .  ja  va2 s .c om
 *
 * @param serializedSpeechletRequest
 *            speechlet request serialized as a string of JSON
 * @param baseEncoded64Signature
 *            the signature for provided in the request header
 * @param signingCertificateChainUrl
 *            the certificate chain URL provided in the request header
 */
public static void checkRequestSignature(final byte[] serializedSpeechletRequest,
        final String baseEncoded64Signature, final String signingCertificateChainUrl) {
    if ((baseEncoded64Signature == null) || (signingCertificateChainUrl == null)) {
        throw new SecurityException("Missing signature/certificate for the provided speechlet request");
    }

    try {
        X509Certificate signingCertificate;
        if (CERTIFICATE_CACHE.containsKey(signingCertificateChainUrl)) {
            signingCertificate = CERTIFICATE_CACHE.get(signingCertificateChainUrl);
            /*
             * check the before/after dates on the certificate are still valid for the present
             * time
             */
            signingCertificate.checkValidity();
        } else {
            signingCertificate = retrieveAndVerifyCertificateChain(signingCertificateChainUrl);

            // if certificate is valid, then add it to the cache
            CERTIFICATE_CACHE.put(signingCertificateChainUrl, signingCertificate);
        }

        // verify that the request was signed by the provided certificate
        Signature signature = Signature.getInstance(Sdk.SIGNATURE_ALGORITHM);
        signature.initVerify(signingCertificate.getPublicKey());
        signature.update(serializedSpeechletRequest);
        if (!signature.verify(Base64.decodeBase64(baseEncoded64Signature.getBytes(Sdk.CHARACTER_ENCODING)))) {
            throw new SecurityException(
                    "Failed to verify the signature/certificate for the provided speechlet request");
        }
    } catch (CertificateException | SignatureException | NoSuchAlgorithmException | InvalidKeyException
            | IOException ex) {
        throw new SecurityException(
                "Failed to verify the signature/certificate for the provided speechlet request", ex);
    }
}

From source file:netinf.common.security.impl.SignatureAlgorithmImpl.java

/**
 * @see SignatureAlgorithm#sign(String, PrivateKey, String)
 *//*from  w ww.j av a2s  .c  o  m*/
@Override
public String sign(String originalString, PrivateKey sk, String hashAndSignatureFunction)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Signature signature = Signature.getInstance(hashAndSignatureFunction);
    signature.initSign(sk);
    signature.update(originalString.getBytes());
    return Base64.encodeBase64String(signature.sign());
}

From source file:com.turo.pushy.apns.auth.ApnsSigningKey.java

/**
 * Constructs a new signing key with the given key identifier, team identifier, and elliptic curve private key.
 *
 * @param keyId the ten-character, Apple-issued identifier for the key itself
 * @param teamId the ten-character, Apple-issued identifier for the team to which the key belongs
 * @param key the elliptic curve public key underpinning this verification key
 *
 * @throws NoSuchAlgorithmException if the {@value APNS_SIGNATURE_ALGORITHM} algorith is not supported by the JVM
 * @throws InvalidKeyException if the given elliptic curve private key is invalid for any reason
 *///from w  w  w .ja va 2 s.c  o m
public ApnsSigningKey(final String keyId, final String teamId, final ECPrivateKey key)
        throws NoSuchAlgorithmException, InvalidKeyException {
    super(keyId, teamId, key);

    // This is a little goofy, but we want to check early for missing algorithms or bogus keys, and the most direct
    // way to do that is to try to actually use the key to create a signature.
    final Signature signature = Signature.getInstance(ApnsKey.APNS_SIGNATURE_ALGORITHM);
    signature.initSign(key);
}