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:edu.ucsb.eucalyptus.cloud.ws.HttpTransfer.java

public HttpMethodBase constructHttpMethod(String verb, String addr, String eucaOperation, String eucaHeader) {
    String date = new Date().toString();
    String httpVerb = verb;//from www. j a  v  a  2 s  .c  o m
    String addrPath;
    try {
        java.net.URI addrUri = new URL(addr).toURI();
        addrPath = addrUri.getPath().toString();
        String query = addrUri.getQuery();
        if (query != null) {
            addrPath += "?" + query;
        }
    } catch (Exception ex) {
        LOG.error(ex, ex);
        return null;
    }
    String data = httpVerb + "\n" + date + "\n" + addrPath + "\n";

    HttpMethodBase method = null;
    if (httpVerb.equals("PUT")) {
        method = new PutMethodWithProgress(addr);
    } else if (httpVerb.equals("DELETE")) {
        method = new DeleteMethod(addr);
    } else {
        method = new GetMethod(addr);
    }
    method.setRequestHeader("Authorization", "Euca");
    method.setRequestHeader("Date", date);
    //method.setRequestHeader("Expect", "100-continue");
    method.setRequestHeader(StorageProperties.EUCALYPTUS_OPERATION, eucaOperation);
    if (eucaHeader != null) {
        method.setRequestHeader(StorageProperties.EUCALYPTUS_HEADER, eucaHeader);
    }
    try {
        PrivateKey ccPrivateKey = SystemCredentials.lookup(Storage.class).getPrivateKey();
        Signature sign = Signature.getInstance("SHA1withRSA");
        sign.initSign(ccPrivateKey);
        sign.update(data.getBytes());
        byte[] sig = sign.sign();

        method.setRequestHeader("EucaSignature", new String(Base64.encode(sig)));
    } catch (Exception ex) {
        LOG.error(ex, ex);
    }
    return method;
}

From source file:org.ejbca.util.keystore.KeyTools.java

/** Testing a key pair to verify that it is possible to first sign and then verify with it.
 * /*from  www.j  ava2 s.com*/
 * @param priv private key to sign a string with
 * @param pub public key to verify the signature with
 * @param provider A provider used for signing with the private key, or null if "BC" should be used.
 * 
 * @throws InvalidKeyException if the public key can not be used to verify a string signed by the private key, because the key is wrong or the signature operation fails for other reasons such as a NoSuchAlgorithmException or SignatureException.
 * @throws NoSuchProviderException if the provider is not installed.
 */
public static void testKey(final PrivateKey priv, final PublicKey pub, final String provider)
        throws InvalidKeyException, NoSuchProviderException {
    final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes();
    final byte signBV[];
    final String testSigAlg;
    {
        final Iterator<String> i = AlgorithmTools.getSignatureAlgorithms(pub).iterator();
        final String tmp = i.hasNext() ? i.next() : null;
        testSigAlg = tmp != null ? tmp : "SHA1WithRSA";
    }
    if (log.isDebugEnabled()) {
        log.debug("Testing keys with algorithm: " + pub.getAlgorithm());
        log.debug("testSigAlg: " + testSigAlg);
        log.debug("provider: " + provider);
        log.trace("privateKey: " + priv);
        log.trace("privateKey class: " + priv.getClass().getName());
        log.trace("publicKey: " + pub);
        log.trace("publicKey class: " + pub.getClass().getName());
    }
    try {
        {
            final Provider prov = Security.getProvider(provider != null ? provider : "BC");
            final Signature signature = Signature.getInstance(testSigAlg, prov);
            signature.initSign(priv);
            signature.update(input);
            signBV = signature.sign();
            if (signBV == null) {
                throw new InvalidKeyException("Result from signing is null.");
            }
            if (log.isDebugEnabled()) {
                log.trace("Created signature of size: " + signBV.length);
                log.trace("Created signature: " + new String(Hex.encode(signBV)));
            }
        }
        {
            final Signature signature = Signature.getInstance(testSigAlg, "BC");
            signature.initVerify(pub);
            signature.update(input);
            if (!signature.verify(signBV)) {
                throw new InvalidKeyException("Not possible to sign and then verify with key pair.");
            }
        }
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e);
    } catch (SignatureException e) {
        throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e);
    }
}

From source file:RGSDigestTools.SignatureTool.java

public String sign(String dataToSign)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, UnsupportedEncodingException {
    Signature signer = Signature.getInstance(signAlg);
    signer.initSign(signKey);/*from   ww w .j  a  v a 2s  . c o m*/
    signer.update(dataToSign.getBytes("Windows-1251"));
    return bytesToHex(signer.sign());//Base64.encodeBase64String(signer.sign());//bytesToHex(signer.sign());

}

From source file:RGSDigestTools.SignatureTool.java

public boolean verify(String dataToVerify, byte[] signature)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, UnsupportedEncodingException {
    Signature signer = Signature.getInstance(signAlg);
    signer.initVerify(verifyKey);//from  w w  w.  j ava  2s. co m
    signer.update(dataToVerify.getBytes());
    return signer.verify(signature);

}

From source file:com.streamsets.datacollector.publicrestapi.CredentialsDeploymentResource.java

private boolean validateSignature(CredentialsBeanJson credentialsBeanJson)
        throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
    // getProperty so we can test it
    String publicKey = Preconditions.checkNotNull(System.getProperty(DPM_AGENT_PUBLIC_KEY));

    X509EncodedKeySpec kspec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(kspec);
    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initVerify(key);/*from   ww w  .j  a v a  2s.c o m*/
    sig.update(credentialsBeanJson.getToken().getBytes(Charsets.UTF_8));
    LOG.info("Token : {}, Signature {}", credentialsBeanJson.getToken(),
            credentialsBeanJson.getTokenSignature());
    return sig.verify(Base64.getDecoder().decode(credentialsBeanJson.getTokenSignature()));
}

From source file:org.digidoc4j.signers.PKCS11SignatureToken.java

private byte[] invokeSigning(byte[] digestToSign, PrivateKey privateKey, String signatureAlgorithm)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    logger.debug("Signing with signature algorithm " + signatureAlgorithm);
    java.security.Signature signer = java.security.Signature.getInstance(signatureAlgorithm);
    signer.initSign(privateKey);//w  w  w .  j  a va  2s.  co m
    signer.update(digestToSign);
    byte[] signatureValue = signer.sign();
    return signatureValue;
}

From source file:org.intermine.webservice.server.JWTBuilder.java

private byte[] sign(String toSign) throws InvalidKeyException, SignatureException {
    Signature signing = algorithm.createSignature();
    signing.initSign(key);//from  ww w .  j  a v  a  2 s  . c om
    signing.update(toSign.getBytes());

    byte[] signature = signing.sign();
    return signature;
}

From source file:com.titilink.common.app.EncryptDecryptUtil.java

public void testRSA() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException, SignatureException {
    ////from  w w w.  ja  v  a  2  s . c om
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    //?
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    //??
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, privateKey, new SecureRandom());
    byte[] cipherData = cipher
            .doFinal("this is a security text from server".getBytes(Charset.forName("UTF-8")));

    //
    Cipher cipher1 = Cipher.getInstance("RSA");
    cipher1.init(Cipher.DECRYPT_MODE, publicKey, new SecureRandom());
    byte[] plainData = cipher1.doFinal(cipherData);
    System.out.println(new String(plainData, Charset.forName("UTF-8")));

    //???????
    Signature signature = Signature.getInstance("MD5withRSA");
    signature.initSign(privateKey);
    signature.update(cipherData);
    byte[] signData = signature.sign();

    //?????
    Signature signature1 = Signature.getInstance("MD5withRSA");
    signature1.initVerify(publicKey);
    signature1.update(cipherData);
    System.out.println(signature1.verify(signData));

}

From source file:org.springframework.security.oauth.common.signature.RSA_SHA1SignatureMethod.java

/**
 * The Signature Base String is signed using the Consumers RSA private key per RFC3447 section 8.2.1, where K is the Consumers RSA private key,
 * M the Signature Base String, and S is the result signature octet string:<br/><br/>
 *
 * S = RSASSA-PKCS1-V1_5-SIGN (K, M)<br/><br/>
 *
 * oauth_signature is set to S, first base64-encoded per RFC2045 section 6.8, then URL-encoded per Parameter Encoding.
 *
 * @param signatureBaseString The signature base string.
 * @return The signature.//from w w  w .j  av  a  2  s.  com
 * @throws UnsupportedOperationException If there is no private key.
 */
public String sign(String signatureBaseString) {
    if (privateKey == null) {
        throw new UnsupportedOperationException("Cannot sign the base string: no private key supplied.");
    }

    try {
        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initSign(privateKey);
        signer.update(signatureBaseString.getBytes("UTF-8"));
        byte[] signatureBytes = signer.sign();
        signatureBytes = Base64.encodeBase64(signatureBytes);
        return new String(signatureBytes, "UTF-8");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException(e);
    } catch (SignatureException e) {
        throw new IllegalStateException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.talend.components.common.oauth.X509Key.java

/**
 * sign data with private key using algo
 *///from   ww  w.j a v a 2  s .  c  o  m
public byte[] sign(String data, Algorithm algo) {

    try {
        // Sign the JWT Header + "." + JWT Claims Object
        Signature signature = Signature.getInstance(algo.name());
        signature.initSign(privateKey);
        signature.update(data.getBytes(charSetUtf8));
        return signature.sign();

    } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        throw new RuntimeException(e);
    }
}