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:cloud.google.oauth2.MyWayAuthentication.java

/**
 * Get signature from private key// w w  w.ja  va  2  s  .  c o  m
 * */
public byte[] signData(byte[] data, PrivateKey privateKey)
        throws InvalidKeyException, SignatureException, NoSuchAlgorithmException {
    Signature signature = Signature.getInstance("SHA256withRSA");
    signature.initSign(privateKey);
    signature.update(data);
    return signature.sign();
}

From source file:org.jvnet.hudson.update_center.Signing.java

/**
 * Generates a canonicalized JSON format of the given object, and put the signature in it.
 * Because it mutates the signed object itself, validating the signature needs a bit of work,
 * but this enables a signature to be added transparently.
 *//*from w w w.  j  a  v  a 2  s  .com*/
public void sign(JSONObject o) throws GeneralSecurityException, IOException {
    JSONObject sign = new JSONObject();

    List<X509Certificate> certs = getCertificateChain();
    X509Certificate signer = certs.get(0); // the first one is the signer, and the rest is the chain to a root CA.

    // this is for computing a digest
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);

    // this is for computing a signature
    PrivateKey key = ((KeyPair) new PEMReader(new FileReader(privateKey)).readObject()).getPrivate();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initSign(key);
    SignatureOutputStream sos = new SignatureOutputStream(sig);

    // this is for verifying that signature validates
    Signature verifier = Signature.getInstance("SHA1withRSA");
    verifier.initVerify(signer.getPublicKey());
    SignatureOutputStream vos = new SignatureOutputStream(verifier);

    o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(new TeeOutputStream(dos, sos), vos), "UTF-8"));

    // digest
    byte[] digest = sha1.digest();
    sign.put("digest", new String(Base64.encodeBase64(digest)));

    // signature
    byte[] s = sig.sign();
    sign.put("signature", new String(Base64.encodeBase64(s)));

    // and certificate chain
    JSONArray a = new JSONArray();
    for (X509Certificate cert : certs)
        a.add(new String(Base64.encodeBase64(cert.getEncoded())));
    sign.put("certificates", a);

    // did the signature validate?
    if (!verifier.verify(s))
        throw new GeneralSecurityException(
                "Signature failed to validate. Either the certificate and the private key weren't matching, or a bug in the program.");

    o.put("signature", sign);
}

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.
 * //w w  w. j  ava2  s. c  o m
 * @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: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 w w  w . j  a v  a  2  s. co 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:test.be.fedict.eid.applet.PKCS11Test.java

@Test
public void testPKCS1viaPKCS11() 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=2");

    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);
    PrivateKey privateKey = privateKeyEntry.getPrivateKey();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);
    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();
    RSAPublicKey publicKey = (RSAPublicKey) certificate.getPublicKey();
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(),
            publicKey.getModulus());
    LOG.debug("original message: " + new String(Hex.encodeHex(messageBigInteger.toByteArray())));

    // LOG.debug("ASN.1 signature: " + ASN1Dump.dumpAsString(obj)
}

From source file:test.be.fedict.eid.applet.PKCS11Test.java

@Test
public void testTokenHasBeenRemovedError() throws Exception {
    File tmpConfigFile = File.createTempFile("pkcs11-", "conf");
    tmpConfigFile.deleteOnExit();/* w w w .  jav a  2s  .  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...");
    {
        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();
    }
}

From source file:com.POLIS.licensing.common.license.AbstractSerializationBasedLicense.java

@Override
public void signLicense(PrivateKey privateSignatureKey)
        throws BadLicenseException, SystemStateException, OperationException {
    try {/*from  w  w w .  j av a2s  .co m*/
        Signature instance = Signature.getInstance(signatureEncoding, provider);
        instance.initSign(privateSignatureKey);
        instance.update(getFieldsAsString().getBytes());
        signature = instance.sign();
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SystemStateException("Could not sign the license. Algorithm not found", ex);
    } catch (InvalidKeyException | SignatureException ex) {
        throw new OperationException("Could not sign the license.", ex);
    }
}

From source file:RGSDigestTools.SignatureTool.java

public String sign(String dataToSign)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, UnsupportedEncodingException {
    Signature signer = Signature.getInstance(signAlg);
    signer.initSign(signKey);
    signer.update(dataToSign.getBytes("Windows-1251"));
    return bytesToHex(signer.sign());//Base64.encodeBase64String(signer.sign());//bytesToHex(signer.sign());

}

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

public void testRSA() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException, SignatureException {
    ///* w  ww  .  j a v  a  2  s.co  m*/
    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.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);
    signer.update(digestToSign);/*from   w  ww. j  a  v a 2s .com*/
    byte[] signatureValue = signer.sign();
    return signatureValue;
}