Example usage for java.security Signature update

List of usage examples for java.security Signature update

Introduction

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

Prototype

public final void update(ByteBuffer data) throws SignatureException 

Source Link

Document

Updates the data to be signed or verified using the specified ByteBuffer.

Usage

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static byte[] getSignatureRS512(byte[] signingInput, RSAPrivateKey rsaPrivateKey)
        throws SignatureException, InvalidKeyException, NoSuchProviderException, InvalidKeySpecException,
        NoSuchAlgorithmException {
    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(),
            rsaPrivateKey.getPrivateExponent());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    PrivateKey privateKey = keyFactory.generatePrivate(rsaPrivateKeySpec);

    Signature signature = Signature.getInstance("SHA512withRSA", "BC");
    signature.initSign(privateKey);// ww w.  ja v  a 2s  .  c o  m
    signature.update(signingInput);

    return signature.sign();
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static byte[] getSignatureES256(byte[] signingInput, ECDSAPrivateKey ecdsaPrivateKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException,
        SignatureException {/*from   w w w.j  a  v a  2  s.  c o m*/
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-256");
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(ecdsaPrivateKey.getD(), ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    Signature signature = Signature.getInstance("SHA256WITHECDSA", "BC");
    signature.initSign(privateKey);
    signature.update(signingInput);

    return signature.sign();
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static byte[] getSignatureES384(byte[] signingInput, ECDSAPrivateKey ecdsaPrivateKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException,
        SignatureException {/*from   www .  ja va  2  s . c o  m*/
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-384");
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(ecdsaPrivateKey.getD(), ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    Signature signature = Signature.getInstance("SHA384WITHECDSA", "BC");
    signature.initSign(privateKey);
    signature.update(signingInput);

    return signature.sign();
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static byte[] getSignatureES512(byte[] signingInput, ECDSAPrivateKey ecdsaPrivateKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException,
        SignatureException {//from   ww w.  j a va2s .  co m
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-521");
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(ecdsaPrivateKey.getD(), ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    Signature signature = Signature.getInstance("SHA512WITHECDSA", "BC");
    signature.initSign(privateKey);
    signature.update(signingInput);

    return signature.sign();
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static boolean verifySignatureES256(byte[] signingInput, byte[] sigBytes, ECDSAPublicKey ecdsaPublicKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        IOException, SignatureException {
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-256");
    BigInteger q = ((ECCurve.Fp) ecSpec.getCurve()).getQ();
    ECFieldElement xFieldElement = new ECFieldElement.Fp(q, ecdsaPublicKey.getX());
    ECFieldElement yFieldElement = new ECFieldElement.Fp(q, ecdsaPublicKey.getY());
    ECPoint pointQ = new ECPoint.Fp(ecSpec.getCurve(), xFieldElement, yFieldElement);
    ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(pointQ, ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    Signature signature = Signature.getInstance("SHA256WITHECDSA", "BC");
    signature.initVerify(publicKey);/*ww  w  .j  ava2 s .c o  m*/
    signature.update(signingInput);
    return signature.verify(sigBytes);
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static boolean verifySignatureES384(byte[] signingInput, byte[] sigBytes, ECDSAPublicKey ecdsaPublicKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        IOException, SignatureException {
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-384");
    BigInteger q = ((ECCurve.Fp) ecSpec.getCurve()).getQ();
    ECFieldElement xFieldElement = new ECFieldElement.Fp(q, ecdsaPublicKey.getX());
    ECFieldElement yFieldElement = new ECFieldElement.Fp(q, ecdsaPublicKey.getY());
    ECPoint pointQ = new ECPoint.Fp(ecSpec.getCurve(), xFieldElement, yFieldElement);
    ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(pointQ, ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    Signature signature = Signature.getInstance("SHA384WITHECDSA", "BC");
    signature.initVerify(publicKey);//from  w  ww.  j  a  v  a  2 s.co m
    signature.update(signingInput);
    return signature.verify(sigBytes);
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static boolean verifySignatureES512(byte[] signingInput, byte[] sigBytes, ECDSAPublicKey ecdsaPublicKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        IOException, SignatureException {
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-521");
    BigInteger q = ((ECCurve.Fp) ecSpec.getCurve()).getQ();
    ECFieldElement xFieldElement = new ECFieldElement.Fp(q, ecdsaPublicKey.getX());
    ECFieldElement yFieldElement = new ECFieldElement.Fp(q, ecdsaPublicKey.getY());
    ECPoint pointQ = new ECPoint.Fp(ecSpec.getCurve(), xFieldElement, yFieldElement);
    ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(pointQ, ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    Signature signature = Signature.getInstance("SHA512WITHECDSA", "BC");
    signature.initVerify(publicKey);/*from   w  w w  .  java 2 s  . c  om*/
    signature.update(signingInput);
    return signature.verify(sigBytes);
}

From source file:Manifest.java

/**
 * This method verifies the digital signature of the named manifest file, if
 * it has one, and if that verification succeeds, it verifies the message
 * digest of each file in filelist that is also named in the manifest. This
 * method can throw a bunch of exceptions
 *//*from w  w  w  . j a  va2s  . com*/
public static void verify(String manifestfile, KeyStore keystore) throws NoSuchAlgorithmException,
        SignatureException, InvalidKeyException, KeyStoreException, IOException {
    Properties manifest = new Properties();
    manifest.load(new FileInputStream(manifestfile));
    String digestAlgorithm = manifest.getProperty("__META.DIGESTALGORITHM");
    String signername = manifest.getProperty("__META.SIGNER");
    String signatureAlgorithm = manifest.getProperty("__META.SIGNATUREALGORITHM");
    String hexsignature = manifest.getProperty("__META.SIGNATURE");

    // Get a list of filenames in the manifest.
    List files = new ArrayList();
    Enumeration names = manifest.propertyNames();
    while (names.hasMoreElements()) {
        String s = (String) names.nextElement();
        if (!s.startsWith("__META"))
            files.add(s);
    }
    int numfiles = files.size();

    // If we've got a signature but no keystore, warn the user
    if (signername != null && keystore == null)
        System.out.println("Can't verify digital signature without " + "a keystore.");

    // If the manifest contained metadata about a digital signature, then
    // verify that signature first
    if (signername != null && keystore != null) {
        System.out.print("Verifying digital signature...");
        System.out.flush();

        // To verify the signature, we must process the files in exactly
        // the same order we did when we created the signature. We
        // guarantee this order by sorting the filenames.
        Collections.sort(files);

        // Create a Signature object to do signature verification with.
        // Initialize it with the signer's public key from the keystore
        Signature signature = Signature.getInstance(signatureAlgorithm);
        PublicKey publickey = keystore.getCertificate(signername).getPublicKey();
        signature.initVerify(publickey);

        // Now loop through these files in their known sorted order For
        // each one, send the bytes of the filename and of the digest to
        // the signature object for use in computing the signature. It is
        // important that this be done in exactly the same order when
        // verifying the signature as it was done when creating the
        // signature.
        for (int i = 0; i < numfiles; i++) {
            String filename = (String) files.get(i);
            signature.update(filename.getBytes());
            signature.update(hexDecode(manifest.getProperty(filename)));
        }

        // Now decode the signature read from the manifest file and pass
        // it to the verify() method of the signature object. If the
        // signature is not verified, print an error message and exit.
        if (!signature.verify(hexDecode(hexsignature))) {
            System.out.println("\nManifest has an invalid signature");
            System.exit(0);
        }

        // Tell the user we're done with this lengthy computation
        System.out.println("verified.");
    }

    // Tell the user we're starting the next phase of verification
    System.out.print("Verifying file message digests");
    System.out.flush();

    // Get a MessageDigest object to compute digests
    MessageDigest md = MessageDigest.getInstance(digestAlgorithm);
    // Loop through all files
    for (int i = 0; i < numfiles; i++) {
        String filename = (String) files.get(i);
        // Look up the encoded digest from the manifest file
        String hexdigest = manifest.getProperty(filename);
        // Compute the digest for the file.
        byte[] digest;
        try {
            digest = getFileDigest(filename, md);
        } catch (IOException e) {
            System.out.println("\nSkipping " + filename + ": " + e);
            continue;
        }

        // Encode the computed digest and compare it to the encoded digest
        // from the manifest. If they are not equal, print an error
        // message.
        if (!hexdigest.equals(hexEncode(digest)))
            System.out.println("\nFile '" + filename + "' failed verification.");

        // Send one dot of output for each file we process. Since
        // computing message digests takes some time, this lets the user
        // know that the program is functioning and making progress
        System.out.print(".");
        System.out.flush();
    }
    // And tell the user we're done with verification.
    System.out.println("done.");
}

From source file:org.dasein.cloud.google.GoogleMethod.java

static @Nonnull String getToken(@Nonnull String iss, @Nonnull String p12File) throws CloudException {
    if (logger.isDebugEnabled()) {
        logger.debug("iss: " + iss);
        logger.debug("p12File: " + p12File);
    }//from w  ww . j a  va  2 s .  c  o  m

    String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    StringBuffer token = new StringBuffer();

    try {
        token.append(Base64.encodeBase64URLSafeString(header.getBytes("UTF-8")));

        token.append(".");

        String scope = "https://www.googleapis.com/auth/compute";
        String aud = "https://accounts.google.com/o/oauth2/token";
        String expiry = Long.toString((System.currentTimeMillis() / 1000) + 3600);
        String startTime = Long.toString((System.currentTimeMillis() / 1000));

        String payload = "{\"iss\": \"" + iss + "\", \"scope\": \"" + scope + "\", \"aud\": \"" + aud
                + "\", \"exp\": \"" + expiry + "\", \"iat\": \"" + startTime + "\"}";

        token.append(Base64.encodeBase64URLSafeString(payload.getBytes("UTF-8")));

        // TODO: the password is hardcoded. This has to be read from the ctx or from the environment variable
        char[] password = "notasecret".toCharArray();
        FileInputStream iStream = new FileInputStream(new File(p12File));
        KeyStore store = KeyStore.getInstance("PKCS12");
        try {
            store.load(iStream, password);
        } finally {
            try {
                iStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("Could not read the keystore file");
                throw new CloudException(e);
            }
        }
        String alias = "";

        Enumeration<String> aliases = store.aliases();
        while (aliases.hasMoreElements()) {
            String keyStoreAlias = aliases.nextElement().toString();
            if (store.isKeyEntry(keyStoreAlias)) {
                alias = keyStoreAlias;
                break;
            }
        }

        PrivateKey privateKey = (PrivateKey) store.getKey(alias, password);

        Signature shaSignature = Signature.getInstance("SHA256withRSA");
        shaSignature.initSign(privateKey);
        shaSignature.update(token.toString().getBytes("UTF-8"));
        String signedToken = Base64.encodeBase64URLSafeString(shaSignature.sign());

        //Separate with a period
        token.append(".");

        //Add the encoded signature
        token.append(signedToken);
        return token.toString();

    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Could not sign the payload with the private key");
        throw new CloudException(e);
    }
}

From source file:org.chaston.oakfunds.xsrf.XsrfSigner.java

public boolean verify(String material, String signature) throws GeneralSecurityException {
    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initVerify(certificate);/*from   w w  w.ja  v a 2  s .c  om*/
    sig.update(material.getBytes(CHARSET));
    return sig.verify(Base64.decodeBase64(signature));
}