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:com.muk.services.commerce.CryptoServiceImpl.java

@Override
public String signature(String algorithm, String payload, PrivateKey privateKey) {
    Signature signator;
    String signedPayload = "Failed";

    try {/*from   w ww . ja v  a2  s  .com*/
        signator = Signature.getInstance(algorithm);
        signator.initSign(privateKey);
        signator.update(payload.getBytes(StandardCharsets.UTF_8));
        signedPayload = encodeUrlSafe(signator.sign());
    } catch (final SignatureException sigEx) {
        LOG.error("Failed to sign payload.", sigEx);
    } catch (final InvalidKeyException keyEx) {
        LOG.error("Failed initialize with private key.", keyEx);
    } catch (final NoSuchAlgorithmException algEx) {
        LOG.error("Failed getting signature.", algEx);
    }

    return signedPayload;

}

From source file:com.xinferin.licensing.LicenceGenerator.java

/**
 * Signs the data and returns the signature.
 * @param toBeSigned Data to be signed/*from www.  j  ava  2  s  .c om*/
 * @return byte[] Signature
 * @throws Exception 
*/
public byte[] signData(byte[] toBeSigned) throws Exception {

    try {
        if (privateKey == null)
            initialisePrivateKey();

        Signature signatureInstance = Signature.getInstance("SHA1withRSA");
        signatureInstance.initSign(privateKey);
        signatureInstance.update(toBeSigned);

        return signatureInstance.sign();

    } catch (NoSuchAlgorithmException ex) {
        throw new Exception("The SHA1withRSA algorithm was not found. " + ex.getCause());
    } catch (InvalidKeyException in) {
        throw new Exception("Invalid key returned from database. " + in.getCause());
    } catch (SignatureException se) {
        throw new Exception("No signature instance can be created. " + se.getCause());
    }
}

From source file:org.p2pvpn.tools.AdvProperties.java

/**
 * Verify a signature.//from  w w  w  . ja va2 s .co  m
 * @param keyName name if the signature key.
 * @param publicKey the public key of the signature
 * @return signature correct?
 */
public boolean verify(String keyName, PublicKey publicKey) {
    try {
        byte[] data = filter(keyName, true).asBytes();
        Signature signature = CryptoUtils.getSignature();
        signature.initVerify(publicKey);
        signature.update(data);
        return signature.verify(getPropertyBytes(keyName, null));
    } catch (Throwable ex) {
        Logger.getLogger("").log(Level.SEVERE, null, ex);
        return false;
    }
}

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

@Test
public void testTokenHasBeenRemovedWorkaround() throws Exception {
    File tmpConfigFile = File.createTempFile("pkcs11-", "conf");
    tmpConfigFile.deleteOnExit();//from  w  w  w. j  av a 2s. co 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:com.cedarsoft.crypt.X509Support.java

/**
 * <p>verifySignature</p>/*from   w w w .  j  a v  a 2s .co  m*/
 *
 * @param plainText an array of byte.
 * @param signature a com.cedarsoft.crypt.Signature object.
 * @return a boolean.
 *
 * @throws GeneralSecurityException
 *          if any.
 */
public boolean verifySignature(@Nonnull byte[] plainText, @Nonnull com.cedarsoft.crypt.Signature signature)
        throws GeneralSecurityException {
    Signature sign = Signature.getInstance(SHA_256_WITH_RSA);
    sign.initVerify(certificate);
    sign.update(plainText);
    return sign.verify(signature.getBytes());
}

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 .  jav  a  2 s .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.turo.pushy.apns.AuthenticationToken.java

public AuthenticationToken(final ApnsSigningKey signingKey, final Date issuedAt)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    this.header = new AuthenticationTokenHeader(signingKey.getKeyId());
    this.claims = new AuthenticationTokenClaims(signingKey.getTeamId(), issuedAt);

    final String headerJson = GSON.toJson(this.header);
    final String claimsJson = GSON.toJson(this.claims);

    final StringBuilder payloadBuilder = new StringBuilder();
    payloadBuilder.append(Base64.encodeBase64URLSafeString(headerJson.getBytes(StandardCharsets.US_ASCII)));
    payloadBuilder.append('.');
    payloadBuilder.append(Base64.encodeBase64URLSafeString(claimsJson.getBytes(StandardCharsets.US_ASCII)));

    {/* ww  w  . jav a2s  .c  o  m*/
        final Signature signature = Signature.getInstance(ApnsKey.APNS_SIGNATURE_ALGORITHM);
        signature.initSign(signingKey);
        signature.update(payloadBuilder.toString().getBytes(StandardCharsets.US_ASCII));

        this.signatureBytes = signature.sign();
    }

    payloadBuilder.append('.');
    payloadBuilder.append(Base64.encodeBase64URLSafeString(this.signatureBytes));

    this.base64EncodedToken = payloadBuilder.toString();
}

From source file:mx.bigdata.sat.cfd.CFDv2.java

public void verificar(Certificate cert) throws Exception {
    String sigStr = document.getSello();
    Base64 b64 = new Base64();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    boolean md5 = true;
    if (getYear() < 2011) {
        Signature sig = Signature.getInstance("MD5withRSA");
        sig.initVerify(cert);/* w  ww. jav a 2 s  .  c  o m*/
        sig.update(bytes);
        try {
            sig.verify(signature);
        } catch (SignatureException e) {
            // Not MD5
            md5 = false;
        }
    }
    if (getYear() > 2010 || !md5) {
        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(cert);
        sig.update(bytes);
        boolean bool = sig.verify(signature);
        if (!bool) {
            throw new Exception("Invalid signature");
        }
    }
}

From source file:hudson.cli.Connection.java

/**
 * Used in conjunction with {@link #verifyIdentity(byte[])} to prove
 * that we actually own the private key of the given key pair.
 *//* w  ww. jav  a2s.co m*/
public void proveIdentity(byte[] sharedSecret, KeyPair key) throws IOException, GeneralSecurityException {
    String algorithm = detectKeyAlgorithm(key);
    writeUTF(algorithm);
    writeKey(key.getPublic());

    Signature sig = Signature.getInstance("SHA1with" + algorithm);
    sig.initSign(key.getPrivate());
    sig.update(key.getPublic().getEncoded());
    sig.update(sharedSecret);
    writeObject(sig.sign());
}

From source file:com.turo.pushy.apns.AuthenticationToken.java

public boolean verifySignature(final ApnsVerificationKey verificationKey)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    if (!this.header.getKeyId().equals(verificationKey.getKeyId())) {
        return false;
    }//from w ww  . j  a v a  2 s  .  c  o m

    if (!this.claims.getIssuer().equals(verificationKey.getTeamId())) {
        return false;
    }

    final byte[] headerAndClaimsBytes;

    final String headerJson = GSON.toJson(this.header);
    final String claimsJson = GSON.toJson(this.claims);

    final StringBuilder headerAndClaimsBuilder = new StringBuilder();

    headerAndClaimsBuilder
            .append(Base64.encodeBase64URLSafeString(headerJson.getBytes(StandardCharsets.US_ASCII)));
    headerAndClaimsBuilder.append('.');
    headerAndClaimsBuilder
            .append(Base64.encodeBase64URLSafeString(claimsJson.getBytes(StandardCharsets.US_ASCII)));

    headerAndClaimsBytes = headerAndClaimsBuilder.toString().getBytes(StandardCharsets.US_ASCII);

    final Signature signature = Signature.getInstance(ApnsKey.APNS_SIGNATURE_ALGORITHM);
    signature.initVerify(verificationKey);
    signature.update(headerAndClaimsBytes);

    return signature.verify(this.signatureBytes);
}