Example usage for java.security Signature getInstance

List of usage examples for java.security Signature getInstance

Introduction

In this page you can find the example usage for java.security Signature getInstance.

Prototype

public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Signature object that implements the specified signature algorithm.

Usage

From source file:org.opensaml.security.crypto.SigningUtil.java

/**
 * Compute the raw signature value over the supplied input.
 * /*www  .  ja  v a  2 s  . co  m*/
 * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of signing key
 * supplied.
 * 
 * @param signingKey the private key with which to compute the signature
 * @param jcaAlgorithmID the Java JCA algorithm ID to use
 * @param input the input over which to compute the signature
 * @return the computed signature value
 * @throws SecurityException thrown if the signature computation results in an error
 */
@Nonnull
public static byte[] sign(@Nonnull final PrivateKey signingKey, @Nonnull final String jcaAlgorithmID,
        @Nonnull final byte[] input) throws SecurityException {
    Constraint.isNotNull(signingKey, "Private key cannot be null");
    Constraint.isNotNull(jcaAlgorithmID, "JCA algorithm ID cannot be null");
    Constraint.isNotNull(input, "Input data to sign cannot be null");

    Logger log = getLogger();
    log.debug("Computing signature over input using private key of type {} and JCA algorithm ID {}",
            signingKey.getAlgorithm(), jcaAlgorithmID);

    try {
        Signature signature = Signature.getInstance(jcaAlgorithmID);
        signature.initSign(signingKey);
        signature.update(input);
        byte[] rawSignature = signature.sign();
        log.debug("Computed signature: {}", Hex.encodeHex(rawSignature));
        return rawSignature;
    } catch (GeneralSecurityException e) {
        log.error("Error during signature generation", e);
        throw new SecurityException("Error during signature generation", e);
    }
}

From source file:com.zxy.commons.codec.rsa.RSAUtils.java

/**
 * <p>/*w ww .  j a v  a  2 s .  com*/
 * ??
 * </p>
 * 
 * @param data ?
 * @param publicKey (BASE64?)
 * @param sign ??
 * 
 * @return boolean
 * @throws Exception Exception
 * 
 */
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(publicKey);
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PublicKey publicK = keyFactory.generatePublic(keySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initVerify(publicK);
    signature.update(data);
    return signature.verify(Base64.decodeBase64(sign));
}

From source file:test.unit.be.fedict.eid.applet.service.signer.CMSTest.java

@Test
public void testPkcs1Signature() throws Exception {
    // setup/*from  w w  w  . j a  v  a  2s  .  c  o m*/
    KeyPair keyPair = PkiTestUtils.generateKeyPair();
    byte[] toBeSigned = "hello world".getBytes();

    // operate
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(keyPair.getPrivate());
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    // verify
    signature.initVerify(keyPair.getPublic());
    signature.update(toBeSigned);
    boolean signatureResult = signature.verify(signatureValue);
    assertTrue(signatureResult);
}

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  v a  2  s.com*/
    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:org.apache.james.jmap.crypto.JamesSignatureHandler.java

@Override
public boolean verify(String source, String signature) {
    Preconditions.checkNotNull(source);/*from   w  w w.  j av a  2s . co m*/
    Preconditions.checkNotNull(signature);
    try {
        Signature javaSignature = Signature.getInstance(ALGORITHM);
        javaSignature.initVerify(publicKey);
        javaSignature.update(source.getBytes());
        return javaSignature.verify(new Base64().decode(signature));
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw Throwables.propagate(e);
    } catch (SignatureException e) {
        LOGGER.warn("Attempt to use a malformed signature '" + signature + "' for source '" + source + "'", e);
        return false;
    }
}

From source file:gemlite.core.util.RSAUtils.java

/**
 * <p>//from   w w  w .  j av  a 2s . c o m
 * ?????
 * </p>
 * 
 * @param data
 *          ?
 * @param privateKey
 *          ?(BASE64?)
 * 
 * @return
 * @throws Exception
 */
public static String sign(byte[] data, String privateKey) throws Exception {
    byte[] keyBytes = Base64Utils.decode(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(privateK);
    signature.update(data);
    return Base64Utils.encode(signature.sign());
}

From source file:dk.itst.oiosaml.sp.service.util.Utils.java

/**
 * Check if a SAML HTTP Redirect has been signed by the expected certificate
 * /*from  www .  j  av a  2 s  .  c o m*/
 * @param data
 *            The query parameters in the HTTP Redirect, which has been
 *            signed
 * @param key
 *            The public key of the certificate from the expected sender
 * @param sig
 *            The signature generated by the sender after it has been base64
 *            decoded
 * @return true, if the signature is valid, otherwise false
 */
public static boolean verifySignature(byte[] data, PublicKey key, byte[] sig) {

    if (log.isDebugEnabled())
        log.debug("data...:" + new String(data));
    if (log.isDebugEnabled())
        log.debug("sig....:" + new String(sig));
    if (log.isDebugEnabled())
        log.debug("key....:" + key.toString());

    try {
        Signature signer = Signature.getInstance(OIOSAMLConstants.SHA1_WITH_RSA);
        signer.initVerify(key);
        signer.update(data);
        return signer.verify(sig);
    } catch (InvalidKeyException e) {
        throw new WrappedException(Layer.CLIENT, e);
    } catch (NoSuchAlgorithmException e) {
        throw new WrappedException(Layer.CLIENT, e);
    } catch (SignatureException e) {
        throw new WrappedException(Layer.CLIENT, e);
    }
}

From source file:org.wso2.carbon.device.mgt.iot.transport.CommunicationUtils.java

/**
 * Signed a given message using the PrivateKey that's passes in.
 *
 * @param message      the message to be signed. Ideally some encrypted payload.
 * @param signatureKey the PrivateKey with which the message is to be signed.
 * @return the Base64Encoded String of the signed payload.
 * @throws TransportHandlerException if some error occurs with the signing process which may be related to the
 *                                   signature algorithm used or the key used for signing.
 *///from www  .j a  va  2s.  c o  m
public static String signMessage(String message, PrivateKey signatureKey) throws TransportHandlerException {

    Signature signature;
    String signedEncodedString;

    try {
        signature = Signature.getInstance(SIGNATURE_ALG);
        signature.initSign(signatureKey);
        signature.update(Base64.decodeBase64(message));

        byte[] signatureBytes = signature.sign();
        signedEncodedString = Base64.encodeBase64String(signatureBytes);

    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm not found exception occurred for Signature instance of [" + SIGNATURE_ALG
                + "]";
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature exception occurred for Signature instance of [" + SIGNATURE_ALG + "]";
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, e);
    } catch (InvalidKeyException e) {
        String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + signatureKey + "\n]\n";
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, e);
    }
    return signedEncodedString;
}

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

public int verificar() throws Exception {
    if (tfd == null) {
        return 601; //No contiene timbrado
    }/*  w  w w . j  ava2  s  .com*/
    Base64 b64 = new Base64();
    String sigStr = tfd.getSelloSAT();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(cert);
    sig.update(bytes);
    boolean verified = sig.verify(signature);
    return verified ? 600 : 602; //Sello del timbrado no valido
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.CommunicationUtils.java

/**
 * Signed a given message using the PrivateKey that's passes in.
 *
 * @param message      the message to be signed. Ideally some encrypted payload.
 * @param signatureKey the PrivateKey with which the message is to be signed.
 * @return the Base64Encoded String of the signed payload.
 * @throws TransportHandlerException if some error occurs with the signing process which may be related to the
 *                                     signature algorithm used or the key used for signing.
 *///from   w w w. jav  a  2  s  .c  o  m
public static String signMessage(String message, PrivateKey signatureKey) throws TransportHandlerException {

    Signature signature;
    String signedEncodedString;

    try {
        signature = Signature.getInstance(SHA_512);
        signature.initSign(signatureKey);
        signature.update(Base64.decodeBase64(message));

        byte[] signatureBytes = signature.sign();
        signedEncodedString = Base64.encodeBase64String(signatureBytes);

    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm not found exception occurred for Signature instance of [" + SHA_512 + "]";
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature exception occurred for Signature instance of [" + SHA_512 + "]";
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, e);
    } catch (InvalidKeyException e) {
        String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + signatureKey + "\n]\n";
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, e);
    }

    return signedEncodedString;
}