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:mx.bigdata.sat.cfdi.CFDv3.java

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  w  ww. j a v  a 2s  .  c o m
    sig.update(bytes);
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature");
    }
}

From source file:com.jinhe.tss.core.common.license.LicenseManager.java

/**
 * ?license??//ww  w  . j  a v a 2  s  .c  om
 * ?Mac??????
 * ???????
 * 
 * @param license
 * @return
 * @throws Exception
 */
boolean validate(License license) throws Exception {
    String macAddress = license.getMacAddress();
    if (macAddress != null && macAddress.length() > 0) {
        String curMacAddress = MacAddressUtil.getMacAddress();
        if (!macAddress.equals(curMacAddress))
            return false;
    }
    String publicKey = FileHelper.readFile(new File(LicenseFactory.PUBLIC_KEY_FILE)).trim();

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(EasyUtils.decodeHex(publicKey));
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    java.security.PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Signature sig = Signature.getInstance("DSA");
    sig.initVerify(pubKey);
    sig.update(license.getFingerprint());
    return sig.verify(EasyUtils.decodeHex(license.getLicenseSignature()));
}

From source file:com.sixsq.slipstream.cookie.CryptoUtils.java

/**
 * Sign the given data and return a String representation of the signature.
 * The argument may not be null./*from   w ww. j  a  v a  2s .  com*/
 *
 * @param data
 *            information to sign
 *
 * @return String representation of the signature.
 */
public static String sign(String data) {

    try {

        Signature signature = Signature.getInstance(signatureAlgorithm);
        signature.initSign(privateKey);

        signature.update(data.getBytes());
        BigInteger biSignature = new BigInteger(signature.sign());
        return biSignature.toString(radix);

    } catch (NoSuchAlgorithmException nsae) {
        return null;
    } catch (InvalidKeyException ike) {
        return null;
    } catch (SignatureException se) {
        return null;
    }
}

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

@Test
public void testSignAuthnCertCredential() throws Exception {
    LOG.debug("sign");
    // operate//  w  w  w  .j  a va 2  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.znsx.util.licence.LicenceUtil.java

/**
 * ???//w  ww.j  av  a  2  s .c o  m
 * 
 * @param data
 *            ??
 * @param publicKeyString
 *            ??base64?
 * @param signature
 *            base64????
 * @return
 * @throws Exception
 */
public static boolean verify(String data, String publicKeyString, String signature) throws Exception {
    // ???
    // BASE64Decoder decoder = new BASE64Decoder();
    // byte[] bytes = decoder.decodeBuffer(publicKeyString);
    Base64 base64 = new Base64();
    byte[] bytes = base64.decode(publicKeyString.getBytes("utf8"));
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
    PublicKey publicKey = KeyFactory.getInstance("DSA").generatePublic(keySpec);
    // ?
    Signature sign = Signature.getInstance("DSA");
    sign.initVerify(publicKey);
    sign.update(data.getBytes("utf8"));
    // return sign.verify(decoder.decodeBuffer(signature));
    return sign.verify(base64.decode(signature.getBytes("utf8")));
}

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. j a  va  2s  . c  om
    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:com.titilink.common.app.EncryptDecryptUtil.java

public void testRSA() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException, SignatureException {
    ////  ww  w. jav a  2  s .  co  m
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    //?
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    //??
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, privateKey, new SecureRandom());
    byte[] cipherData = cipher
            .doFinal("this is a security text from server".getBytes(Charset.forName("UTF-8")));

    //
    Cipher cipher1 = Cipher.getInstance("RSA");
    cipher1.init(Cipher.DECRYPT_MODE, publicKey, new SecureRandom());
    byte[] plainData = cipher1.doFinal(cipherData);
    System.out.println(new String(plainData, Charset.forName("UTF-8")));

    //???????
    Signature signature = Signature.getInstance("MD5withRSA");
    signature.initSign(privateKey);
    signature.update(cipherData);
    byte[] signData = signature.sign();

    //?????
    Signature signature1 = Signature.getInstance("MD5withRSA");
    signature1.initVerify(publicKey);
    signature1.update(cipherData);
    System.out.println(signature1.verify(signData));

}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.SecurityManager.java

public static String signMessage(String encryptedData, PrivateKey signatureKey)
        throws VirtualFireAlarmException {

    Signature signature;//  ww w.  j  av  a2 s.  c  om
    String signedEncodedString;

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

        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 VirtualFireAlarmException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature exception occurred for Signature instance of [" + SIGNATURE_ALG + "]";
        log.error(errorMsg);
        throw new VirtualFireAlarmException(errorMsg, e);
    } catch (InvalidKeyException e) {
        String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + signatureKey + "\n]\n";
        log.error(errorMsg);
        throw new VirtualFireAlarmException(errorMsg, e);
    }

    return signedEncodedString;
}

From source file:cn.usually.common.pay.union.sdk.SecureUtil.java

/**
 * ???//w  w w  .j  a  v  a  2 s.c  o  m
 * 
 * @param publicKey
 *            
 * @param signData
 *            ???
 * @param srcData
 *            ?
 * @param validateMethod
 *            ??.
 * @return
 * @throws Exception
 */
public static boolean validateSignBySoft(PublicKey publicKey, byte[] signData, byte[] srcData)
        throws Exception {
    Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA1RSA);
    st.initVerify(publicKey);
    st.update(srcData);
    return st.verify(signData);
}

From source file:com.eucalyptus.auth.euare.EuareServerCertificateUtil.java

public static boolean verifySignature(final String certPem, final String msg, final String sigB64) {
    try {//w  ww . ja  v  a 2 s  . c om
        final Signature sig = Signature.getInstance("SHA256withRSA");
        final X509Certificate cert = PEMFiles.getCert(B64.standard.dec(certPem));
        sig.initVerify(cert);
        sig.update(msg.getBytes("UTF-8"));
        return sig.verify(B64.standard.dec(sigB64.getBytes()));
    } catch (final Exception ex) {
        throw Exceptions.toUndeclared(ex);
    }
}