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: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);
    sig.update(bytes);//  w w  w .  j  a  v a  2s.co m
    byte[] signed = sig.sign();
    Base64 b64 = new Base64(-1);
    return b64.encodeToString(signed);
}

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 . j a  v  a2s  . co  m*/
        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:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

@Test
public void testSignAuthnCertCredential() throws Exception {
    LOG.debug("sign");
    // operate//from  w  w w.  jav a2 s .com
    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.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);
}

From source file:org.apache.james.jdkim.IscheduleDKIMSigner.java

private byte[] signatureSign(final Headers h, final SignatureRecord sign, final PrivateKey key,
        final List<CharSequence> headers)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, PermFailException {

    Signature signature = Signature.getInstance(sign.getHashMethod().toString().toUpperCase() + "with"
            + sign.getHashKeyType().toString().toUpperCase());
    signature.initSign(key);

    signatureCheck(h, sign, headers, signature);
    return signature.sign();
}

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)));

    {/*from w  w  w.j  a  v  a  2s. 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:org.apache.james.jdkim.DKIMSigner.java

private byte[] signatureSign(Headers h, SignatureRecord sign, PrivateKey key, List<CharSequence> headers)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, PermFailException {

    Signature signature = Signature.getInstance(sign.getHashMethod().toString().toUpperCase() + "with"
            + sign.getHashKeyType().toString().toUpperCase());
    signature.initSign(key);

    signatureCheck(h, sign, headers, signature);
    return signature.sign();
}

From source file:com.cedarsoft.crypt.X509Support.java

/**
 * <p>sign</p>//  w  ww.  j av a2 s  .  c o  m
 *
 * @param plainText an array of byte.
 * @return a com.cedarsoft.crypt.Signature object.
 *
 * @throws GeneralSecurityException
 *          if any.
 */
@Nonnull
public com.cedarsoft.crypt.Signature sign(@Nonnull byte[] plainText) throws GeneralSecurityException {
    Signature signature = Signature.getInstance(SHA_256_WITH_RSA);
    signature.initSign(getPrivateKey());

    signature.update(plainText);
    return new com.cedarsoft.crypt.Signature(signature.sign());
}

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.
 *///from w w  w.ja  va2  s  .  com
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:org.cesecore.keys.util.KeyTools.java

/**
 * Sign provided data with specified private key and algortihm
 * //from   www.jav  a2s  .com
 * @param privateKey
 *            the private key
 * @param signatureAlgorithm a valid signature algorithm
 * @param data
 *            the data to sign
 * @return the signature
 */
public static byte[] signData(final PrivateKey privateKey, final String signatureAlgorithm, final byte[] data)
        throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
    final Signature signer = Signature.getInstance(signatureAlgorithm);
    signer.initSign(privateKey);
    signer.update(data);
    return (signer.sign());
}