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.xk72.cocoafob.LicenseGenerator.java

/**
 * Verify the given license for the given {@link LicenseData}.
 * @param licenseData/* ww  w .  j a v a  2s  .c o  m*/
 * @param license
 * @return Whether the license verified successfully.
 * @throws LicenseGeneratorException If the verification encounters an error, usually due to invalid input. You MUST check the return value of this method if no exception is thrown.
 * @throws IllegalStateException If the generator is not setup correctly to verify licenses.
 */
public boolean verifyLicense(LicenseData licenseData, String license)
        throws LicenseGeneratorException, IllegalStateException {
    if (!isCanVerifyLicenses()) {
        throw new IllegalStateException(
                "The LicenseGenerator cannot verify licenses as it was not configured with a public key");
    }

    final String stringData = licenseData.toLicenseStringData();

    /* replace O with 8 and I with 9 */
    String licenseSignature = license.replace("8", "O").replace("9", "I");

    /* remove dashes */
    licenseSignature = licenseSignature.replace("-", "");

    /* Pad the output length to a multiple of 8 with '=' characters */
    while (licenseSignature.length() % 8 != 0) {
        licenseSignature += "=";
    }

    byte[] decoded = new Base32().decode(licenseSignature);
    try {
        Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");
        dsa.initVerify(publicKey);
        dsa.update(stringData.getBytes("UTF-8"));
        return dsa.verify(decoded);
    } catch (NoSuchAlgorithmException e) {
        throw new LicenseGeneratorException(e);
    } catch (NoSuchProviderException e) {
        throw new LicenseGeneratorException(e);
    } catch (InvalidKeyException e) {
        throw new LicenseGeneratorException(e);
    } catch (SignatureException e) {
        throw new LicenseGeneratorException(e);
    } catch (UnsupportedEncodingException e) {
        throw new LicenseGeneratorException(e);
    }
}

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

public void postSign(byte[] signatureValue, List<X509Certificate> signingCertificateChain) {
    LOG.debug("postSign");

    String signatureValueStr = new String(Hex.encodeHex(signatureValue));

    HttpSession session = getHttpSession();
    session.setAttribute("SignatureValue", signatureValueStr);
    session.setAttribute("SigningCertificateChain", signingCertificateChain);

    boolean signatureValid = false;
    String toBeSigned = (String) session.getAttribute("toBeSigned");
    LOG.debug("to be signed: " + toBeSigned);
    String digestAlgo = (String) session.getAttribute("digestAlgo");
    String signAlgo = digestAlgoToSignAlgo.get(digestAlgo);

    try {// w w  w.  ja  v a  2  s  .  c om
        Signature signature = Signature.getInstance(signAlgo, BouncyCastleProvider.PROVIDER_NAME);
        signature.initVerify(signingCertificateChain.get(0).getPublicKey());
        signature.update(toBeSigned.getBytes());
        signatureValid = signature.verify(signatureValue);
    } catch (Exception e) {
        LOG.error("error validating the signature: " + e.getMessage(), e);
    }

    session.setAttribute("SignatureValid", signatureValid);
}

From source file:mx.bigdata.sat.cfdi.TFDv1_v32.java

String getSignature(PrivateKey key) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initSign(key);/* www. j a v a2  s . c o  m*/
    sig.update(bytes);
    byte[] signed = sig.sign();
    Base64 b64 = new Base64(-1);
    return b64.encodeToString(signed);
}

From source file:org.xdi.oxauth.model.jws.RSASigner.java

@Override
public String generateSignature(String signingInput) throws SignatureException {
    if (getSignatureAlgorithm() == null) {
        throw new SignatureException("The signature algorithm is null");
    }//from  w  ww  .  ja v  a  2  s  .c  o m
    if (rsaPrivateKey == null) {
        throw new SignatureException("The RSA private key is null");
    }
    if (signingInput == null) {
        throw new SignatureException("The signing input is null");
    }

    try {
        RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(),
                rsaPrivateKey.getPrivateExponent());

        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
        PrivateKey privateKey = keyFactory.generatePrivate(rsaPrivateKeySpec);

        Signature signature = Signature.getInstance(getSignatureAlgorithm().getAlgorithm(), "BC");
        signature.initSign(privateKey);
        signature.update(signingInput.getBytes(Util.UTF8_STRING_ENCODING));

        return JwtUtil.base64urlencode(signature.sign());
    } catch (InvalidKeySpecException e) {
        throw new SignatureException(e);
    } catch (InvalidKeyException e) {
        throw new SignatureException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException(e);
    } catch (NoSuchProviderException e) {
        throw new SignatureException(e);
    } catch (SignatureException e) {
        throw new SignatureException(e);
    } catch (UnsupportedEncodingException e) {
        throw new SignatureException(e);
    } catch (Exception e) {
        throw new SignatureException(e);
    }
}

From source file:eu.europa.esig.dss.extension.AbstractTestExtension.java

protected SignatureValue sign(SignatureAlgorithm algo, MockPrivateKeyEntry privateKey, ToBeSigned bytesToSign)
        throws GeneralSecurityException {
    final Signature signature = Signature.getInstance(algo.getJCEId());
    signature.initSign(privateKey.getPrivateKey());
    signature.update(bytesToSign.getBytes());
    final byte[] signatureValue = signature.sign();
    return new SignatureValue(algo, signatureValue);
}

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  ww .ja  v  a 2  s .  com
    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 "";
}

From source file:com.xk72.cocoafob.LicenseGenerator.java

/**
 * Make and return a license for the given {@link LicenseData}.
 * @param licenseData/*from w ww  .  j a v  a  2s .c o m*/
 * @return
 * @throws LicenseGeneratorException If the generation encounters an error, usually due to invalid input.
 * @throws IllegalStateException If the generator is not setup correctly to make licenses.
 */
public String makeLicense(LicenseData licenseData) throws LicenseGeneratorException, IllegalStateException {
    if (!isCanMakeLicenses()) {
        throw new IllegalStateException(
                "The LicenseGenerator cannot make licenses as it was not configured with a private key");
    }

    final String stringData = licenseData.toLicenseStringData();

    try {
        final Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");
        dsa.initSign(privateKey, random);
        dsa.update(stringData.getBytes("UTF-8"));

        final byte[] signed = dsa.sign();

        /* base 32 encode the signature */
        String result = new Base32().encodeAsString(signed);

        /* replace O with 8 and I with 9 */
        result = result.replace("O", "8").replace("I", "9");

        /* remove padding if any. */
        result = result.replace("=", "");

        /* chunk with dashes */
        result = split(result, 5);
        return result;
    } catch (NoSuchAlgorithmException e) {
        throw new LicenseGeneratorException(e);
    } catch (NoSuchProviderException e) {
        throw new LicenseGeneratorException(e);
    } catch (InvalidKeyException e) {
        throw new LicenseGeneratorException(e);
    } catch (SignatureException e) {
        throw new LicenseGeneratorException(e);
    } catch (UnsupportedEncodingException e) {
        throw new LicenseGeneratorException(e);
    }
}

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

@Test
public void testTokenHasBeenRemovedError() throws Exception {
    File tmpConfigFile = File.createTempFile("pkcs11-", "conf");
    tmpConfigFile.deleteOnExit();/*from  w ww. j  a va 2s.  c  om*/
    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:Version2LicenseDecoder.java

private byte[] checkAndGetLicenseText(String licenseContent) {
    try {/*from   w w  w . j a va 2s  .  c  om*/
        byte[] e = Base64.decodeBase64(licenseContent.getBytes());
        ByteArrayInputStream in = new ByteArrayInputStream(e);
        DataInputStream dIn = new DataInputStream(in);
        int textLength = dIn.readInt();
        byte[] licenseText = new byte[textLength];
        dIn.read(licenseText);
        byte[] hash = new byte[dIn.available()];
        dIn.read(hash);

        try {
            Signature e1 = Signature.getInstance("SHA1withDSA");
            e1.initVerify(PUBLIC_KEY);
            e1.update(licenseText);
            if (!e1.verify(hash)) {
                throw new LicenseException("Failed to verify the license.");
            } else {
                return licenseText;
            }
        } catch (InvalidKeyException var9) {
            throw new LicenseException(var9);
        } catch (SignatureException var10) {
            throw new LicenseException(var10);
        } catch (NoSuchAlgorithmException var11) {
            throw new LicenseException(var11);
        }
    } catch (IOException var12) {
        throw new LicenseException(var12);
    }
}

From source file:com.vmware.identity.sts.auth.impl.UserCertAuthenticatorTest.java

@Test
public void testOK() throws Exception {
    com.vmware.identity.sts.idm.Authenticator idmAuth = EasyMock
            .createMock(com.vmware.identity.sts.idm.Authenticator.class);

    final PrincipalId principalIdc13d = new PrincipalId(name, "acme.com");

    EasyMock.expect(idmAuth.authenticate(EasyMock.isA(X509Certificate[].class))).andReturn(principalIdc13d);
    EasyMock.replay(idmAuth);/*w  ww. j  a  v a 2 s. c  o  m*/

    final Authenticator authenticator = new UserCertAuthenticator(idmAuth);

    final SecurityHeaderType header = new SecurityHeaderType();
    final UserCertificateTokenType userCertiticateToken = new UserCertificateTokenType();
    BinarySecurityTokenType binarySecurityToken = new BinarySecurityTokenType();
    binarySecurityToken.setValueType(X509_CERTIFICATE_TYPE);
    binarySecurityToken.setEncodingType(ENCODING_TYPE_BASE64);
    // base64 encode the x509 certificate
    binarySecurityToken.setValue(new String(Base64.encodeBase64(x509Certificate.getEncoded())));
    userCertiticateToken.setUserCertificate(binarySecurityToken);

    userCertiticateToken.setSignatureInfo(signedInfo);
    userCertiticateToken.setSignatureAlgorithm(SignatureAlgorithmType.SHA_256_WITH_RSA);

    SignatureValueType signatureValueType = new SignatureValueType();
    Signature dsa = Signature.getInstance("SHA256withRSA");
    dsa.initSign(userPrivateKey);
    dsa.update(signedInfo.getBytes());
    signatureValueType.setValue(dsa.sign());
    userCertiticateToken.setSignatureValue(signatureValueType);

    ObjectFactory objectFactory = new ObjectFactory();
    header.getAny().add(objectFactory.createUserCertificateToken(userCertiticateToken));

    final Result authResult = authenticator.authenticate(newReq(header));
    Assert.assertNotNull(authResult);
    Assert.assertTrue(authResult.completed());
    Assert.assertEquals(principalIdc13d, authResult.getPrincipalId());
    Assert.assertEquals(Result.AuthnMethod.SMARTCARD, authResult.getAuthnMethod());

    EasyMock.verify(idmAuth);
}