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:net.sf.dsig.query.QuerystringStrategy.java

@Override
public String signPlaintext(String plaintext, PrivateKey privateKey, X509Certificate[] certificateChain)
        throws Exception {
    Signature signature = Signature.getInstance(signatureAlgorithm);
    signature.initSign(privateKey);//w w  w . ja va2s  . c  o m
    signature.update(plaintext.getBytes());

    String signatureAsBase64 = signInternal(plaintext, privateKey);

    String serialNumberAsString = serialNumberInHexadecimal
            ? HexStringHelper.toHexString(certificateChain[0].getSerialNumber().toByteArray())
            : "" + certificateChain[0].getSerialNumber();

    return "{ \"signature\": \"" + signatureAsBase64 + "\", \"serialNumber\": \"" + serialNumberAsString
            + "\" }";
}

From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java

protected static PKIMessage genRenewalReq(X500Name userDN, Certificate cacert, byte[] nonce, byte[] transid,
        KeyPair keys, boolean raVerifiedPopo, X500Name reqSubjectDN, String reqIssuerDN,
        AlgorithmIdentifier pAlg, DEROctetString senderKID) throws IOException, NoSuchAlgorithmException,
        InvalidKeyException, SignatureException, CertificateEncodingException {

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    myCertTemplate.setValidity(myOptionalValidity);

    if (reqSubjectDN != null) {
        myCertTemplate.setSubject(reqSubjectDN);
    }/*from  w w w.  j  a  v  a  2 s . co  m*/
    if (reqIssuerDN != null) {
        myCertTemplate.setIssuer(new X500Name(reqIssuerDN));
    }

    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    // POPO
    /*
     * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8,
     * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 }));
     * 
     * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new
     * byte[] { 44 }), 2); //take choice pos tag 2
     * 
     * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput(
     * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2,
     * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 }));
     */
    ProofOfPossession myProofOfPossession = null;
    if (raVerifiedPopo) {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEROutputStream mout = new DEROutputStream(baos);
        mout.writeObject(myCertRequest);
        mout.close();
        byte[] popoProtectionBytes = baos.toByteArray();
        String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm())
                .getId();
        Signature sig = Signature.getInstance(sigalg);
        sig.initSign(keys.getPrivate());
        sig.update(popoProtectionBytes);

        DERBitString bs = new DERBitString(sig.sign());

        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    }

    // myCertReqMsg.addRegInfo(new AttributeTypeAndValue(new
    // ASN1ObjectIdentifier("1.3.6.2.2.2.2.3.1"), new
    // DERInteger(1122334455)));
    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String("foo123"));
    AttributeTypeAndValue[] avs = { av };

    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN),
            new GeneralName(new JcaX509CertificateHolder((X509Certificate) cacert).getSubject()));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(pAlg);
    myPKIHeader.setSenderKID(senderKID);

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    return myPKIMessage;

}

From source file:service.GoogleCalendarAuth.java

public GoogleCalendarAuth(String client_id, String key) {
    final long now = System.currentTimeMillis() / 1000L;
    final long exp = now + 3600;
    final char[] password = "notasecret".toCharArray();
    final String claim = "{\"iss\":\"" + client_id + "\"," + "\"scope\":\"" + SCOPE + "\","
            + "\"aud\":\"https://accounts.google.com/o/oauth2/token\"," + "\"exp\":" + exp + "," +
            // "\"prn\":\"some.user@somecorp.com\"," + // This require some.user to have their email served from a googlemail domain?
            "\"iat\":" + now + "}";
    try {//w  w  w .ja  v a 2s. c  o  m
        final String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "."
                + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8"));
        final byte[] jwt_data = jwt.getBytes("UTF8");
        final Signature sig = Signature.getInstance("SHA256WithRSA");

        final KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream(key), password);

        sig.initSign((PrivateKey) ks.getKey("privatekey", password));
        sig.update(jwt_data);
        final byte[] signatureBytes = sig.sign();
        final String b64sig = Base64.encodeBase64URLSafeString(signatureBytes);

        final String assertion = jwt + "." + b64sig;
        //System.out.println("Assertion: " + assertion);
        final String data = "grant_type=assertion" + "&assertion_type="
                + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8") + "&assertion="
                + URLEncoder.encode(assertion, "UTF-8");

        // Make the Access Token Request
        URLConnection conn = null;
        try {
            final URL url = new URL("https://accounts.google.com/o/oauth2/token");
            conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                if (line.split(":").length > 0)
                    if (line.split(":")[0].trim().equals("\"access_token\""))
                        access_token = line.split(":")[1].trim().replace("\"", "").replace(",", "");
                System.out.println(line);
            }
            wr.close();
            rd.close();
        } catch (Exception ex) {
            final InputStream error = ((HttpURLConnection) conn).getErrorStream();
            final BufferedReader br = new BufferedReader(new InputStreamReader(error));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null)
                sb.append(line);
            System.out.println("Error: " + ex + "\n " + sb.toString());
        }
        System.out.println("access_token=" + access_token);
    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
}

From source file:com.streamsets.datacollector.publicrestapi.TestCredentialsDeploymentResource.java

@Test
public void testSuccess() throws Exception {
    Properties sdcProps = new Properties();
    sdcProps.setProperty("a", "b");
    sdcProps.setProperty("c", "d");
    sdcProps.setProperty("kerberos.client.keytab", "sdc.keytab");
    sdcProps.setProperty("kerberos.client.enabled", "false");
    sdcProps.setProperty("kerberos.client.principal", "sdc/_HOST@EXAMPLE.COM");
    File sdcFile = new File(RuntimeInfoTestInjector.confDir, "sdc.properties");

    Properties dpmProps = new Properties();
    dpmProps.setProperty("x", "y");
    dpmProps.setProperty("z", "a");
    dpmProps.setProperty("dpm.enabled", "false");
    dpmProps.setProperty("dpm.base.url", "http://localhost:18631");
    File dpmFile = new File(RuntimeInfoTestInjector.confDir, "dpm.properties");

    try (FileWriter fw = new FileWriter(sdcFile)) {
        sdcProps.store(fw, "");
    }//from  www . j av  a2  s.c om

    try (FileWriter fw = new FileWriter(dpmFile)) {
        dpmProps.store(fw, "");
    }

    Response response = null;
    KeyPair keys = generateKeys();
    mockCheckForCredentialsRequiredToTrue();
    System.setProperty(DPM_AGENT_PUBLIC_KEY, Base64.getEncoder().encodeToString(keys.getPublic().getEncoded()));
    String token = "Frenchies and Pandas";
    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initSign(keys.getPrivate());
    sig.update(token.getBytes(Charsets.UTF_8));
    List<String> labels = Arrays.asList("deployment-prod-1", "deployment-prod-2");
    CredentialsBeanJson json = new CredentialsBeanJson(token, "streamsets/172.1.1.0@EXAMPLE.COM",
            Base64.getEncoder().encodeToString("testKeytab".getBytes(Charsets.UTF_8)),
            Base64.getEncoder().encodeToString(sig.sign()), "https://dpm.streamsets.com:18631",
            Arrays.asList("deployment-prod-1", "deployment-prod-2"), "deployment1:org");

    try {
        response = target("/v1/deployment/deployCredentials").request().post(Entity.json(json));
        Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
        CredentialDeploymentResponseJson responseJson = OBJECT_MAPPER
                .readValue((InputStream) response.getEntity(), CredentialDeploymentResponseJson.class);
        Assert.assertEquals(CredentialDeploymentStatus.CREDENTIAL_USED_AND_DEPLOYED,
                responseJson.getCredentialDeploymentStatus());

        // Verify sdc.properties
        sdcProps = new Properties();
        try (FileReader fr = new FileReader(sdcFile)) {
            sdcProps.load(fr);
        }
        Assert.assertEquals("b", sdcProps.getProperty("a"));
        Assert.assertEquals("d", sdcProps.getProperty("c"));
        Assert.assertEquals("streamsets/172.1.1.0@EXAMPLE.COM",
                sdcProps.getProperty("kerberos.client.principal"));
        Assert.assertEquals("true", sdcProps.getProperty("kerberos.client.enabled"));
        Assert.assertEquals("sdc.keytab", sdcProps.getProperty("kerberos.client.keytab"));
        byte[] keyTab = Files.toByteArray(new File(RuntimeInfoTestInjector.confDir, "sdc.keytab"));
        Assert.assertEquals("testKeytab", new String(keyTab, Charsets.UTF_8));
        response = target("/v1/definitions").request().get();
        Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

        dpmProps = new Properties();
        try (FileReader fr = new FileReader(dpmFile)) {
            dpmProps.load(fr);
        }
        Assert.assertEquals("y", dpmProps.getProperty("x"));
        Assert.assertEquals("a", dpmProps.getProperty("z"));
        Assert.assertEquals("true", dpmProps.getProperty("dpm.enabled"));
        Assert.assertEquals(
                Configuration.FileRef.PREFIX + "application-token.txt" + Configuration.FileRef.SUFFIX,
                dpmProps.getProperty("dpm.appAuthToken"));
        Assert.assertEquals("https://dpm.streamsets.com:18631", dpmProps.getProperty("dpm.base.url"));

        Assert.assertEquals(StringUtils.join(labels.toArray(), ","),
                dpmProps.getProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS));
        Assert.assertEquals("deployment1:org", dpmProps.getProperty(RemoteSSOService.DPM_DEPLOYMENT_ID));

        File tokenFile = new File(RuntimeInfoTestInjector.confDir, "application-token.txt");
        try (FileInputStream fr = new FileInputStream(tokenFile)) {
            int len = token.length();
            byte[] tokenBytes = new byte[len];
            Assert.assertEquals(len, fr.read(tokenBytes));
            Assert.assertEquals(token, new String(tokenBytes, Charsets.UTF_8));
        }
        //Test redeploying the credentials again
        response = target("/v1/deployment/deployCredentials").request().post(Entity.json(json));
        responseJson = OBJECT_MAPPER.readValue((InputStream) response.getEntity(),
                CredentialDeploymentResponseJson.class);
        Assert.assertEquals(CredentialDeploymentStatus.CREDENTIAL_NOT_USED_ALREADY_DEPLOYED,
                responseJson.getCredentialDeploymentStatus());

    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Testing a key pair to verify that it is possible to first sign and then verify with it.
 * /*from  w ww  .  java 2 s .  com*/
 * @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 { // NOPMD:this is not a junit test
    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)));
            }
        }
        {
            Signature signature;
            try {
                signature = Signature.getInstance(testSigAlg, "BC");
            } catch (NoSuchProviderException e) {
                throw new IllegalStateException("BouncyCastle was not found as a provider.", e);
            }
            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:com.aqnote.shared.cryptology.asymmetric.DSA.java

/**
 * ???//from   w  w w .  ja  va2s.  c  o m
 * 
 * @param content ????
 * @param keyPairName key pair
 * @return base64???
 */
public String sign(byte[] content, String keyPairName) throws RuntimeException {
    KeyPairEntry entry = (KeyPairEntry) keyPairs.get(keyPairName);
    if (entry == null || entry.privateKey == null) {
        return null;
    }

    try {
        Signature signature = Signature.getInstance(ALGORITHM);
        signature.initSign(entry.privateKey);
        signature.update((byte[]) content);
        byte[] signed = signature.sign();

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

        return Base64.encodeBase64String(signed);
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.kuzumeji.platform.standard.SecurityService.java

/**
 * ?/*from  ww  w .ja  v  a2 s.  com*/
 * <dl>
 * <dt>?
 * <dd>SHA-512?RSA????????
 * </dl>
 * @param key ?
 * @param signature ??
 * @param plain 
 * @return ?
 */
public boolean verify(final PublicKey key, final byte[] signature, final byte[] plain) {
    try {
        final Signature verifier = Signature.getInstance(SIGN_ALGO_NAME);
        verifier.initVerify(key);
        verifier.update(plain);
        return verifier.verify(signature);
    } catch (final NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.springframework.boot.actuate.autoconfigure.cloudfoundry.TokenValidatorTests.java

private String getSignedToken(byte[] header, byte[] claims) throws Exception {
    PrivateKey privateKey = getPrivateKey();
    Signature signature = Signature.getInstance("SHA256WithRSA");
    signature.initSign(privateKey);//  ww  w.j a v  a  2  s  .co  m
    byte[] content = dotConcat(Base64Utils.encodeUrlSafe(header), Base64Utils.encode(claims));
    signature.update(content);
    byte[] crypto = signature.sign();
    byte[] token = dotConcat(Base64Utils.encodeUrlSafe(header), Base64Utils.encodeUrlSafe(claims),
            Base64Utils.encodeUrlSafe(crypto));
    return new String(token, UTF_8);
}

From source file:nl.b3p.viewer.stripes.CycloramaActionBean.java

private byte[] sign(PrivateKey privateKey, String token)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {

    Signature instance = Signature.getInstance(SIG_ALGORITHM);
    instance.initSign(privateKey);/*from w ww.  j  a v  a  2 s  . com*/
    instance.update(token.getBytes());
    byte[] signature = instance.sign();

    return signature;
}

From source file:GCS_Auth.java

public GCS_Auth(String client_id, String key) {
    String SCOPE = "https://www.googleapis.com/auth/shoppingapi";
    SCOPE = SCOPE + " " + "https://www.googleapis.com/auth/structuredcontent";
    try {//from  ww  w . j  av  a 2  s. c  o  m
        String jwt_header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";

        long now = System.currentTimeMillis() / 1000L;
        long exp = now + 3600;
        String iss = client_id;
        String claim = "{\"iss\":\"" + iss + "\",\"scope\":\"" + SCOPE
                + "\",\"aud\":\"https://accounts.google.com/o/oauth2/token\",\"exp\":" + exp + ",\"iat\":" + now
                + "}";

        String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "."
                + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8"));

        byte[] jwt_data = jwt.getBytes("UTF8");

        Signature sig = Signature.getInstance("SHA256WithRSA");

        KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream(key), "notasecret".toCharArray());

        sig.initSign((PrivateKey) ks.getKey("privatekey", "notasecret".toCharArray()));
        sig.update(jwt_data);
        byte[] signatureBytes = sig.sign();
        String b64sig = Base64.encodeBase64URLSafeString(signatureBytes);

        String assertion = jwt + "." + b64sig;

        //System.out.println("Assertion: " + assertion);

        String data = "grant_type=assertion";
        data += "&" + "assertion_type" + "="
                + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8");
        data += "&" + "assertion=" + URLEncoder.encode(assertion, "UTF-8");

        URLConnection conn = null;
        try {
            URL url = new URL("https://accounts.google.com/o/oauth2/token");
            conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                if (line.split(":").length > 0)
                    if (line.split(":")[0].trim().equals("\"access_token\""))
                        access_token = line.split(":")[1].trim().replace("\"", "").replace(",", "");
                System.out.println(line);
            }
            wr.close();
            rd.close();
        } catch (Exception ex) {
            InputStream error = ((HttpURLConnection) conn).getErrorStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(error));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println("Error: " + ex + "\n " + sb.toString());
        }
        //System.out.println(access_token);
    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
}