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:test.be.fedict.eid.applet.PKCS11Test.java

@Test
public void testTokenHasBeenRemovedWorkaround() throws Exception {
    File tmpConfigFile = File.createTempFile("pkcs11-", "conf");
    tmpConfigFile.deleteOnExit();/*w ww.j  a  v a  2  s .  c o  m*/
    PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile), true);
    configWriter.println("name=SmartCard");
    configWriter.println("library=/usr/lib/libbeidpkcs11.so.0");
    configWriter.println("slotListIndex=1");

    SunPKCS11 provider = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(provider);
    {
        KeyStore keyStore = KeyStore.getInstance("PKCS11", provider);
        keyStore.load(null, null);
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null);
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKeyEntry.getPrivateKey());
        byte[] toBeSigned = "hello world".getBytes();
        signature.update(toBeSigned);
        byte[] signatureValue = signature.sign();

    }
    JOptionPane.showMessageDialog(null, "Please remove and re-insert the token...");
    Security.removeProvider(provider.getName());
    {
        SunPKCS11 provider2 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
        Security.addProvider(provider2);
        KeyStore keyStore = KeyStore.getInstance("PKCS11", provider2);
        keyStore.load(null, null);
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null);
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKeyEntry.getPrivateKey());
        byte[] toBeSigned = "hello world".getBytes();
        signature.update(toBeSigned);
        byte[] signatureValue = signature.sign();
        Security.removeProvider(provider2.getName());
    }
}

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./*  ww  w .  ja  v  a 2 s  .co  m*/
 * @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
 *///w ww. j  a  v  a  2s  . co 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);
    }
}

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

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

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

From source file:test.be.fedict.eid.applet.model.AuthenticationSignatureServiceBean.java

public PreSignResult preSign(List<X509Certificate> authnCertificateChain,
        AuthenticationSignatureContext authenticationSignatureContext) {
    LOG.debug("preSign");
    LOG.debug("authn cert chain size: " + authnCertificateChain.size());

    KeyStore proxyKeyStore;//  w w w  . ja  v  a2s. c om
    final ProxyPrivateKey proxyPrivateKey;
    try {
        proxyKeyStore = KeyStore.getInstance("ProxyBeID");
        proxyKeyStore.load(null);
        proxyPrivateKey = (ProxyPrivateKey) proxyKeyStore.getKey("Signature", null);
    } catch (Exception e) {
        throw new RuntimeException("error loading ProxyBeID keystore");
    }

    FutureTask<String> signTask = new FutureTask<String>(new Callable<String>() {
        public String call() throws Exception {
            final Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(proxyPrivateKey);

            final byte[] toBeSigned = "hello world".getBytes();
            signature.update(toBeSigned);
            final byte[] signatureValue = signature.sign();
            LOG.debug("received signature value");
            return "signature result";
        }

    });
    final ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(signTask);

    authenticationSignatureContext.store("key", proxyPrivateKey);
    authenticationSignatureContext.store("signTask", signTask);

    byte[] digestValue;
    try {
        digestValue = proxyPrivateKey.getDigestInfo().getDigestValue();
    } catch (InterruptedException e) {
        throw new RuntimeException("signature error: " + e.getMessage(), e);
    }
    DigestInfo digestInfo = new DigestInfo(digestValue, "SHA-256", "WS-Security message");
    PreSignResult preSignResult = new PreSignResult(digestInfo, true);
    return preSignResult;
}

From source file:com.launchkey.sdk.crypto.JCECrypto.java

/**
 * @see Crypto#sign(byte[])/*w ww  . j a  va  2  s .  c o m*/
 */
public byte[] sign(byte[] message) {
    try {
        Signature signature = getSha256withRSA();
        signature.initSign(privateKey);
        signature.update(message);
        return signature.sign();
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Algorithm SHA256withRSA is not available", e);
    } catch (InvalidKeyException e) {
        throw new IllegalArgumentException("publicKey is not a valid RSA public key", e);
    } catch (SignatureException e) {
        throw new IllegalArgumentException("An error occurred processing the signature", e);
    }
}

From source file:org.structr.util.StructrLicenseManager.java

private static void sign(final Map<String, String> properties, final String keystoreFileName,
        final String password) {

    final String src = collectLicenseFieldsForSignature(properties);

    try {/*w ww  .  ja  v a2s.  c  o m*/

        final byte[] data = src.getBytes(CharSet);
        final Signature signer = Signature.getInstance(SignatureAlgorithm);
        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        try (final InputStream is = new FileInputStream(keystoreFileName)) {

            keyStore.load(is, password.toCharArray());

            final Key key = keyStore.getKey(KeystoreAlias, password.toCharArray());

            signer.initSign((PrivateKey) key);
            signer.update(data);

            properties.put(SignatureKey, Hex.encodeHexString(signer.sign()));
        }

    } catch (Throwable t) {
        logger.warn("Unable to sign license.", t);
    }
}

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 ww  w  .  j a v a 2s  .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);
}

From source file:mx.bigdata.cfdi.CFDv3.java

String getSignature(PrivateKey key) throws Exception {
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initSign(key);
    sig.update(bytes);//from   www  . j av  a 2  s  .c o  m
    byte[] signed = sig.sign();
    Base64 b64 = new Base64(-1);
    return b64.encodeToString(signed);
}

From source file:gui.configurar.GerarAssinatura.java

String assinar() {
    String senha = tSenha.getText();
    String c = tContribuinte.getText() + tDev.getText();
    if (certificado == null) {
        Msg.show("Escolha o certificado");
        return "";
    }/*from w  w w.j  a v  a2 s . co  m*/
    try {
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(new FileInputStream(certificado), senha.toCharArray());
        ArrayList<String> apelidos = new ArrayList<String>();
        Enumeration<String> aliases = keystore.aliases();
        while (aliases.hasMoreElements()) {
            apelidos.add(aliases.nextElement());
        }
        PrivateKey key = (PrivateKey) keystore.getKey(apelidos.get(0), senha.toCharArray());
        Signature assinatura = Signature.getInstance("SHA256withRSA");
        assinatura.initSign(key);
        byte[] bytes = c.getBytes();
        assinatura.update(bytes);
        byte[] assinado = assinatura.sign();
        String strAssinado = Base64.encodeBase64String(assinado);
        return strAssinado;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}