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.apli.modelbeans.facturacion.cfdi.CFDv32.java

@Override
public void verificar() throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory
            .createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER, new ByteArrayInputStream(cbs)).getKey();

    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(cert);/*from  ww  w .  j a va2 s . c  om*/
    sig.update(bytes);
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature");
    }
}

From source file:com.vimukti.accounter.license.LicenseManager.java

public LicensePair doEncode(License license) {

    byte[] licenseText = null;
    byte[] hash;/*from  ww w  .j a va2 s  .  co  m*/
    try {
        licenseText = Zip.compressBytes(new PropertiesPersister().getLicenseAsString(license));
    } catch (UnsupportedEncodingException e) {
        throw new LicenseException(e);
    } catch (IOException e) {
        throw new LicenseException(e);
    }

    try {
        Signature signature = Signature.getInstance("SHA1withDSA");
        signature.initSign(getPrivateKey());
        signature.update(licenseText);
        hash = signature.sign();
    } catch (InvalidKeyException e) {
        throw new LicenseException(e);
    } catch (SignatureException e) {
        throw new LicenseException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new LicenseException(e);
    }

    String packLicense = packLicense(licenseText, hash);

    return new LicensePair(licenseText, hash, packLicense);
}

From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

private void signAndVerify(X509Certificate certificate, PrivateKey privateKey, String signatureAlgo)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Signature signature = Signature.getInstance(signatureAlgo);
    signature.initSign(privateKey);/*from  ww w  .j  a v  a  2  s . c  om*/

    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    assertNotNull(signatureValue);

    signature = Signature.getInstance(signatureAlgo);
    signature.initVerify(certificate.getPublicKey());
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:com.vimukti.accounter.license.LicenseManager.java

private byte[] checkAndGetLicenseText(String licenseContent) {
    byte[] licenseText;
    try {//from  w  w  w. jav  a2s.c  om
        byte[] decodedBytes = Base64.decodeBase64(licenseContent.getBytes());
        ByteArrayInputStream in = new ByteArrayInputStream(decodedBytes);
        DataInputStream dIn = new DataInputStream(in);
        int textLength = dIn.readInt();
        licenseText = new byte[textLength];
        dIn.read(licenseText);
        byte[] hash = new byte[dIn.available()];
        dIn.read(hash);
        try {
            Signature signature = Signature.getInstance("SHA1withDSA");
            signature.initVerify(PUBLIC_KEY);
            signature.update(licenseText);
            if (!signature.verify(hash)) {
                throw new LicenseException("Failed to verify the license.");
            }

        } catch (InvalidKeyException e) {
            throw new LicenseException(e);
        } catch (SignatureException e) {
            throw new LicenseException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new LicenseException(e);
        }

    } catch (IOException e) {
        throw new LicenseException(e);
    }

    return licenseText;
}

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

@Test
public void testPSS() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = new SecureRandom();
    keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    Signature signature = Signature.getInstance("SHA256withRSA/PSS", "BC");

    byte[] data = "hello world".getBytes();

    signature.initSign(privateKey);//from w ww .  ja  v  a  2s.  c o  m
    signature.update(data);
    byte[] signatureValue = signature.sign();

    LOG.debug("signature size: " + signatureValue.length);

    LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue)));

    signature.initVerify(publicKey);
    signature.update(data);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);

    signature.initSign(privateKey);
    signature.update(data);
    byte[] signatureValue2 = signature.sign();

    LOG.debug("signature size: " + signatureValue2.length);

    LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue2)));

    assertFalse(Arrays.equals(signatureValue, signatureValue2));

    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256", "BC");
    byte[] digest = messageDigest.digest(data);

    signature = Signature.getInstance("RAWRSASSA-PSS", "BC");
    signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1));
    signature.initVerify(publicKey);
    signature.update(digest);
    result = signature.verify(signatureValue);
    assertTrue(result);
}

From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

@Test
public void testSignAuthnCertCredential() throws Exception {
    LOG.debug("sign");
    // operate/*from   ww w  . j a v a 2 s.c o  m*/
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    Security.addProvider(new HSMProxyProvider());
    KeyStore hsmProxyKeyStore = KeyStore.getInstance("HSMProxy");

    HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(authnPrivateKey, authnCert,
            "https://www.e-contract.be/hsm-proxy-ws/dss",
            // "http://localhost/hsm-proxy-ws/dss",
            new MyHSMProxyAudit());
    keyStoreParameter.setProxy("proxy.yourict.net", 8080);
    hsmProxyKeyStore.load(keyStoreParameter);

    PrivateKey hsmPrivateKey = (PrivateKey) hsmProxyKeyStore.getKey("alias", null);

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(hsmPrivateKey);

    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    assertNotNull(signatureValue);
}

From source file:com.microsoft.azure.oidc.token.impl.SimpleTokenValidator.java

@Override
public Boolean validateSignature(final Token token) {
    if (token == null) {
        throw new PreconditionException("Required parameter is null");
    }/*from w w w  .  j a  v  a2 s . co m*/
    if (algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName())
            .equals("HMAC")) {
        return Boolean.FALSE;
    }
    final Configuration configuration = configurationCache.load();
    if (configuration == null) {
        throw new GeneralException("Error loading configuration");
    }
    try {
        final TimeStamp now = timeStampFactory.createTimeStamp(System.currentTimeMillis() / 1000);
        if (configuration.getKey(token.getKeyName()).getNotBefore().compareTo(now) > 0) {
            return Boolean.FALSE;
        }
        final Base64 decoder = new Base64();
        final BigInteger exponent = new BigInteger(1,
                decoder.decode(configuration.getKey(token.getKeyName()).getExponent().getValue()));
        final BigInteger modulus = new BigInteger(1,
                decoder.decode(configuration.getKey(token.getKeyName()).getSecret().getValue()));
        final RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, exponent);
        final KeyFactory keyFactory = KeyFactory.getInstance(
                algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName()));
        final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
        final Signature sig = Signature.getInstance(
                algorithmConfigurationService.get().getAlgorithmMap().get(token.getAlgorithm().getName()));
        sig.initVerify(pubKey);
        sig.update(token.getPayload().getValue().getBytes());
        return sig.verify(decoder.decode(token.getSignature().getValue()));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | SignatureException | InvalidKeyException e) {
        LOGGER.error(e.getMessage(), e);
        return Boolean.FALSE;
    }
}

From source file:net.sf.dsig.query.QuerystringStrategy.java

private String signInternal(String plaintext, PrivateKey privateKey) throws Exception {
    Signature signature = Signature.getInstance(signatureAlgorithm);
    signature.initSign(privateKey);//from   ww w. ja v  a  2 s  .  c  o  m
    signature.update(plaintext.getBytes());

    return new String(Base64.encodeBase64(signature.sign()));
}

From source file:com.aqnote.shared.cryptology.asymmetric.DSA.java

/**
 * content??/*from  w ww. j  av a  2s . c  om*/
 * 
 * @param content ?
 * @param signature ??
 * @param keyPairName key pair
 * @return ??<code>true</code>
 */
public boolean verify(byte[] content, String signature, String keyPairName) throws RuntimeException {
    KeyPairEntry entry = (KeyPairEntry) keyPairs.get(keyPairName);
    if (entry == null || entry.publicKey == null) {
        return false;
    }

    try {
        byte[] signed = Base64.decodeBase64(signature);

        if (log.isDebugEnabled()) {
            log.debug("Java signature[length=" + signed.length + "]: " + toHexString(signed));
        }

        Signature sign = Signature.getInstance(ALGORITHM);
        sign.initVerify(entry.publicKey);
        sign.update((byte[]) content);

        return sign.verify(signed);
    } catch (InvalidKeyException e) {
        throw new RuntimeException("Could not check content", e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Could not check content", e);
    } catch (SignatureException e) {
        throw new RuntimeException("Could not check content", e);
    }
}

From source file:org.esupportail.papercut.services.PayBoxService.java

public boolean checkPayboxSignature(String queryString, String signature) {

    String sData = queryString.substring(0, queryString.lastIndexOf("&"));

    try {//from  ww  w .  j av  a 2s.c om
        Signature sig = Signature.getInstance("SHA1WithRSA");
        byte[] sigBytes = Base64.decodeBase64(signature.getBytes());
        sig.initVerify(payboxPublicKey);
        sig.update(sData.getBytes());
        boolean signatureOk = sig.verify(sigBytes);
        if (!signatureOk) {
            log.error("Erreur lors de la vrification de la signature, les donnes ne correspondent pas.");
            log.error(sData);
            log.error(signature);
        }
        return signatureOk;
    } catch (Exception e) {
        log.warn("Pb when checking SSL signature of Paybox", e);
        return false;
    }
}