Java Code Examples for java.security.Signature#update()

The following examples show how to use java.security.Signature#update() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ToolECDSA.java    From protools with Apache License 2.0 6 votes vote down vote up
/**
 * 校验
 *
 * @param data
 *         待校验数据
 * @param publicKey
 *         公钥
 * @param sign
 *         数字签名
 *
 * @return boolean 校验成功返回true 失败返回false
 *
 * @throws Exception
 */
public static boolean verify(byte[] data, byte[] publicKey, byte[] sign) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
    // 加入BouncyCastleProvider支持
    Security.addProvider(new BouncyCastleProvider());

    // 转换公钥材料
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);

    // 实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    // 生成公钥
    PublicKey pubKey = keyFactory.generatePublic(keySpec);

    // 实例化Signature
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);

    // 初始化Signature
    signature.initVerify(pubKey);

    // 更新
    signature.update(data);

    // 验证
    return signature.verify(sign);
}
 
Example 2
Source File: SHA1withRSAUtils.java    From payment with Apache License 2.0 6 votes vote down vote up
/**
 * 校验签名
 * @param publicFilePath 证书路径
 * @param encoding 编码方式
 * @param paramStr 加密字符串
 * @param signStr 签名
    * @return
    */
public static boolean enCodeByCer(String publicFilePath, String encoding,
		String paramStr, String signStr) {

	boolean flag = false;
	try {
		// 获得文件(相对路径)
		InputStream publicStream = SHA1withRSAUtils.class
				.getResourceAsStream(publicFilePath);

		CertificateFactory cf = CertificateFactory.getInstance("X.509");
		X509Certificate cert = (X509Certificate) cf
				.generateCertificate(publicStream);
		// 获得公钥
		PublicKey pk = cert.getPublicKey();
		// 签名
		Signature signature = Signature.getInstance("SHA1withRSA");
		signature.initVerify(pk);
		signature.update(paramStr.getBytes(encoding));
		// 解码
		flag = signature.verify(Base64.decodeBase64(signStr));
	} catch (Exception ex) {
		logger.error("verify failed", ex);
	}
	return flag;
}
 
Example 3
Source File: RSAEncryptor.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
protected String doSign(String content, String charset, String privateKey) throws Exception {
    PrivateKey priKey = getPrivateKeyFromPKCS8(AlipayConstants.SIGN_TYPE_RSA,
            new ByteArrayInputStream(privateKey.getBytes()));

    Signature signature = Signature.getInstance(getSignAlgorithm());

    signature.initSign(priKey);

    if (StringUtils.isEmpty(charset)) {
        signature.update(content.getBytes());
    } else {
        signature.update(content.getBytes(charset));
    }

    byte[] signed = signature.sign();

    return new String(Base64.encodeBase64(signed));
}
 
Example 4
Source File: RevocationAuthority.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Credential Revocation Information object
 *
 * @param key              Private key
 * @param unrevokedHandles Array of unrevoked revocation handles
 * @param epoch            The counter (representing a time window) in which this CRI is valid
 * @param alg              Revocation algorithm
 * @return CredentialRevocationInformation object
 */
public static Idemix.CredentialRevocationInformation createCRI(PrivateKey key, BIG[] unrevokedHandles, int epoch, RevocationAlgorithm alg) throws CryptoException {
    Idemix.CredentialRevocationInformation.Builder builder = Idemix.CredentialRevocationInformation.newBuilder();
    builder.setRevocationAlg(alg.ordinal());
    builder.setEpoch(epoch);

    // Create epoch key
    WeakBB.KeyPair keyPair = WeakBB.weakBBKeyGen();
    if (alg == RevocationAlgorithm.ALG_NO_REVOCATION) {
        // Dummy PK in the proto
        builder.setEpochPk(IdemixUtils.transformToProto(IdemixUtils.genG2));
    } else {
        // Real PK only if we are going to use it
        builder.setEpochPk(IdemixUtils.transformToProto(keyPair.getPk()));
    }

    // Sign epoch + epoch key with the long term key
    byte[] signed;
    try {
        Idemix.CredentialRevocationInformation cri = builder.build();
        Signature ecdsa = Signature.getInstance("SHA256withECDSA");
        ecdsa.initSign(key);
        ecdsa.update(cri.toByteArray());
        signed = ecdsa.sign();

        builder.setEpochPkSig(ByteString.copyFrom(signed));
    } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
        throw new CryptoException("Error processing the signature");
    }

    if (alg == RevocationAlgorithm.ALG_NO_REVOCATION) {
        // build and return the credential information object
        return builder.build();
    } else {
        // If alg not supported, return null
        throw new IllegalArgumentException("Algorithm " + alg.name() + " not supported");
    }
}
 
Example 5
Source File: JwtToken.java    From vipps-developers with MIT License 5 votes vote down vote up
private boolean verifySignature(String alg, String iss, String keyId, String[] tokenValues) throws GeneralSecurityException {
    if (!alg.equals("RS256")) {
        throw new IllegalArgumentException("Illegal algorithm " + alg);
    }
    Signature signature = Signature.getInstance("SHA256withRSA");
    signature.initVerify(CertificateCache.get(keyId, iss));
    signature.update((tokenValues[0] + "." + tokenValues[1]).getBytes());
    return signature.verify(Base64.getUrlDecoder().decode(tokenValues[2]));
}
 
Example 6
Source File: CuentasContablesv11.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
String getSignature(PrivateKey key) throws Exception {
	byte[] bytes = getOriginalBytes();
	Signature sig = Signature.getInstance("SHA1withRSA");
	sig.initSign(key);
	sig.update(bytes);
	byte[] signed = sig.sign();
	Base64 b64 = new Base64(-1);
	return b64.encodeToString(signed);
}
 
Example 7
Source File: GXPkcs10.java    From gurux.dlms.java with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sign
 * 
 * @param kp
 *            Public and Private key.
 * @param hashAlgorithm
 *            Used algorithm for signing.
 */
@SuppressWarnings("squid:S00112")
public void sign(final KeyPair kp, final HashAlgorithm hashAlgorithm) {
    byte[] data = GXAsn1Converter.toByteArray(getdata());
    try {
        Signature instance =
                Signature.getInstance(hashAlgorithm.toString());
        instance.initSign(kp.getPrivate());
        instance.update(data);
        signatureAlgorithm = hashAlgorithm;
        signature = instance.sign();
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 8
Source File: HttpClientSourceIT.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
@POST
public Response post(
    @Context HttpHeaders h,
    @FormParam(OAuth2ConfigBean.GRANT_TYPE_KEY) String type,
    @FormParam(OAuth2ConfigBean.ASSERTION_KEY) String assertion
) throws Exception {
  type = URLDecoder.decode(type, "UTF-8");
  if (!type.equals(JWT_BEARER_TOKEN)) {
    return Response.status(Response.Status.FORBIDDEN).build();
  }
  String[] creds = assertion.split("\\.");
  Signature sig = Signature.getInstance("SHA256WithRSA");
  sig.initSign(keyPair.getPrivate());
  sig.update((creds[0] + "." + creds[1]).getBytes());
  byte[] signatureBytes = sig.sign();
  if (!Arrays.equals(signatureBytes, Base64.decodeBase64(creds[2]))) {
    return Response.status(Response.Status.FORBIDDEN).build();
  }
  String base64dAlg = new String(Base64.decodeBase64(creds[0]));
  String base64dJWT = new String(Base64.decodeBase64(creds[1]));
  if (base64dAlg.equals(ALGORITHM) &&
      base64dJWT.equals(JWT)) {
    token = RandomStringUtils.randomAlphanumeric(16);
    String tokenResponse = "{\n" +
        "  \"token_type\": \"Bearer\",\n" +
        "  \"expires_in\": \"3600\",\n" +
        "  \"ext_expires_in\": \"0\",\n" +
        "  \"expires_on\": \"1484788319\",\n" +
        "  \"not_before\": \"1484784419\",\n" +
        "  \"access_token\": \"" + token + "\"\n" +
        "}";
    tokenGetCount++;
    return Response.ok().entity(tokenResponse).build();
  }
  return Response.status(Response.Status.FORBIDDEN).build();
}
 
Example 9
Source File: TFDv1c32.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
public int verificar() throws Exception {
    if (tfd == null) {
        return 601; //No contiene timbrado
    }
    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
}
 
Example 10
Source File: RSAUtils.java    From rhizobia_J with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @Description: 验签
 * @Param: sign 数字签名
 * @Param: oriData 原始数据
 * @return: boolean 是否通过验签
 */
public boolean verify(byte[] sign, String oriData) throws Exception {
    byte[] data = oriData.getBytes();
    // 实例化Signature
    Signature signature = Signature.getInstance(signatureAlgorithm);
    // 初始化Signature
    signature.initVerify(publicKey);
    // 更新
    signature.update(data);

    return signature.verify(sign);
}
 
Example 11
Source File: TestSignatureOidHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void runTest(OidAlgorithmPair oidAlgorithmPair, KeyPair keyPair)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeyException, SignatureException {
    Signature sgAlgorithm =
            Signature.getInstance(oidAlgorithmPair.algorithm, provider);
    Signature sgOid = Signature.getInstance(oidAlgorithmPair.oid, provider);

    if (sgAlgorithm == null) {
        throw new RuntimeException(String.format(
                "Test failed: algorithm string %s getInstance failed.%n",
                oidAlgorithmPair.algorithm));
    }

    if (sgOid == null) {
        throw new RuntimeException(
                String.format("Test failed: OID %s getInstance failed.%n",
                        oidAlgorithmPair.oid));
    }

    if (!sgAlgorithm.getAlgorithm().equals(oidAlgorithmPair.algorithm)) {
        throw new RuntimeException(String.format(
                "Test failed: algorithm string %s getInstance "
                        + "doesn't generate expected algorithm.%n",
                oidAlgorithmPair.algorithm));
    }

    sgAlgorithm.initSign(keyPair.getPrivate());
    sgAlgorithm.update(INPUT);
    sgOid.initVerify(keyPair.getPublic());
    sgOid.update(INPUT);
    if (!sgOid.verify(sgAlgorithm.sign())) {
        throw new RuntimeException(
                "Signature verification failed unexpectedly");
    }
}
 
Example 12
Source File: KeyUtils.java    From Bitcoin with Apache License 2.0 5 votes vote down vote up
public static final byte[] signMsg(Signature enc, byte[] bytes) {
    byte[] signed = null;
    try {
        enc.update(bytes);
        signed = enc.sign();
    } catch (Exception e) {
        System.err.println("Could not encode msg. "+e);
    }
    return signed;
}
 
Example 13
Source File: RSAUtils.java    From danyuan-application with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 用私钥对信息生成数字签名
 * </p>
 * @param data 已加密数据
 * @param privateKey 私钥(BASE64编码)
 * @return
 * @throws Exception
 */
public static byte[] sign(byte[] data, byte[] 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());
}
 
Example 14
Source File: SM2.java    From littleca with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] sign(byte[] data, PrivateKey privateKey, String signAlgorithm) throws Exception {
	Signature signature = AsymmetricalUtil.getSignatureInstance(signAlgorithm);
	signature.initSign(privateKey);
	signature.update(data);
	return signature.sign();
}
 
Example 15
Source File: NonStandardNames.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = "Hello".getBytes();
        X500Name n = new X500Name("cn=Me");

        CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
        cakg.generate(1024);
        X509Certificate cert = cakg.getSelfCertificate(n, 1000);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{
            new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID),
            new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)),
        });

        Signature s = Signature.getInstance("SHA256withRSA");
        s.initSign(cakg.getPrivateKey());
        s.update(authed.getDerEncoding());
        byte[] sig = s.sign();

        SignerInfo signerInfo = new SignerInfo(
                n,
                cert.getSerialNumber(),
                AlgorithmId.get("SHA-256"),
                authed,
                AlgorithmId.get("SHA256withRSA"),
                sig,
                null
                );

        PKCS7 pkcs7 = new PKCS7(
                new AlgorithmId[] {signerInfo.getDigestAlgorithmId()},
                new ContentInfo(data),
                new X509Certificate[] {cert},
                new SignerInfo[] {signerInfo});

        if (pkcs7.verify(signerInfo, data) == null) {
            throw new Exception("Not verified");
        }
    }
 
Example 16
Source File: DsaTest.java    From wycheproof with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether CVE-2016-0695 has been fixed. Before the April 2016 security update, the SUN
 * provider had a serious flaw that leaked the private key with about 3-5 signatures. In
 * particular, "Sha1WithDSA" always generated 160 bit k's independently of q. Unfortunately, it is
 * easily possible to use 2048 and 3072 bit DSA keys together with SHA1WithDSA. All a user has to
 * do is to use the algorithm name "DSA" instead of "SHA256WithDSA" rsp. "SHA224WithDSA".
 *
 * <p>An algorithm to extract the key from the signatures has been described for example in the
 * paper <a href="http://www.hpl.hp.com/techreports/1999/HPL-1999-90.pdf">Lattice Attacks on
 * Digital Signature Schemes</a> by N.A. Howgrave-Graham, N.P. Smart.
 *
 * <p>This bug is the same as US-CERT: VU # 940388: GnuPG generated ElGamal signatures that leaked
 * the private key.
 */
@SlowTest(providers = {ProviderType.BOUNCY_CASTLE, ProviderType.SPONGY_CASTLE})
@SuppressWarnings("InsecureCryptoUsage")
@Test
public void testBiasSha1WithDSA() throws Exception {
  String hashAlgorithm = "SHA";
  String message = "Hello";
  byte[] messageBytes = message.getBytes("UTF-8");
  byte[] digest = MessageDigest.getInstance(hashAlgorithm).digest(messageBytes);
  BigInteger h = new BigInteger(1, digest);

  KeyPairGenerator generator = java.security.KeyPairGenerator.getInstance("DSA");
  generator.initialize(2048);
  KeyPair keyPair = generator.generateKeyPair();
  DSAPrivateKey priv = (DSAPrivateKey) keyPair.getPrivate();
  Signature signer = Signature.getInstance("DSA");
  try {
    // Private key and selected algorithm by signer do not match.
    // Hence throwing an exception at this point would be the reasonable.
    signer.initSign(priv);
    signer.update(messageBytes);
    byte[] signature = signer.sign();
    BigInteger q = priv.getParams().getQ();
    BigInteger k = extractK(signature, h, priv, true);

    // Now check if k is heavily biased.
    int lengthDiff = q.bitLength() - k.bitLength();
    if (lengthDiff > 32) {
      fail(
          "Severly biased DSA signature:"
              + " len(q)="
              + q.bitLength()
              + " len(k)="
              + k.bitLength());
    }
  } catch (GeneralSecurityException ex) {
    // The key is invalid, hence getting here is reasonable.
    return;
  }
}
 
Example 17
Source File: AsymmetricDemoWithBob.java    From Hands-On-Cryptography-with-Java with MIT License 4 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, SignatureException {
    final String original = "Encrypted inter-personal example from Packt crypto course.";
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048);
    KeyPair alice = keyPairGenerator.generateKeyPair();
    KeyPair bob = keyPairGenerator.generateKeyPair();

    final String cipherName = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
    //Can use other cipher names, like "RSA/ECB/PKCS1Padding"
    Cipher cipher = Cipher.getInstance(cipherName);
    cipher.init(Cipher.ENCRYPT_MODE, bob.getPublic());

    final byte[] originalBytes = original.getBytes(StandardCharsets.UTF_8);
    byte[] cipherTextBytes = cipher.doFinal(originalBytes);

    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initSign(alice.getPrivate());
    sig.update(originalBytes);
    byte[] signatureBytes = sig.sign();

    // Decrypt
    cipher.init(Cipher.DECRYPT_MODE, bob.getPrivate());
    byte[] decryptedBytes = cipher.doFinal(cipherTextBytes);
    String decryptedString = new String(decryptedBytes, StandardCharsets.UTF_8);

    System.out.println("Original:\t" + original);
    System.out.println("Encrypted:\t" + Util.bytesToHex(cipherTextBytes));
    System.out.println("Decrypted:\t" + decryptedString);
    if (!decryptedString.equals(original)) {
        throw new IllegalArgumentException("Encrypted and decrypted text do not match");
    }

    System.out.println("Checking signature...");
    sig.initVerify(alice.getPublic());
    sig.update(decryptedBytes);
    final boolean signatureValid = sig.verify(signatureBytes);
    if (signatureValid) {
        System.out.println("Yes, Alice wrote this. Notice where Alice/Bob keys are used.");
    } else {
        throw new IllegalArgumentException("Signature does not match");
    }
}
 
Example 18
Source File: SignatureLength.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private static void main0(String keyAlgorithm, int keysize,
        String signatureAlgorithm, Provider generatorProvider,
        Provider signerProvider, Provider verifierProvider,
        boolean mayNotThrow) throws Exception {

    KeyPairGenerator generator;
    Signature signer;
    Signature verifier;

    try {
        generator = KeyPairGenerator.getInstance(keyAlgorithm,
                generatorProvider);
        signer = Signature.getInstance(signatureAlgorithm,
                signerProvider);
        verifier = Signature.getInstance(signatureAlgorithm,
                verifierProvider);
    } catch (NoSuchAlgorithmException nsae) {
        // ignore this set of providers
        return;
    }

    byte[] plaintext = "aaa".getBytes("UTF-8");

    // Generate
    generator.initialize(keysize);
    System.out.println("Generating " + keyAlgorithm + " keypair using " +
        generator.getProvider().getName() + " JCE provider");
    KeyPair keypair = generator.generateKeyPair();

    // Sign
    signer.initSign(keypair.getPrivate());
    signer.update(plaintext);
    System.out.println("Signing using " + signer.getProvider().getName() +
        " JCE provider");
    byte[] signature = signer.sign();

    // Invalidate
    System.out.println("Invalidating signature ...");
    byte[] badSignature = new byte[signature.length + 5];
    System.arraycopy(signature, 0, badSignature, 0, signature.length);
    badSignature[signature.length] = 0x01;
    badSignature[signature.length + 1] = 0x01;
    badSignature[signature.length + 2] = 0x01;
    badSignature[signature.length + 3] = 0x01;
    badSignature[signature.length + 4] = 0x01;

    // Verify
    verifier.initVerify(keypair.getPublic());
    verifier.update(plaintext);
    System.out.println("Verifying using " +
        verifier.getProvider().getName() + " JCE provider");

    try {
        boolean valid = verifier.verify(badSignature);
        System.out.println("Valid? " + valid);
        if (mayNotThrow) {
            if (valid) {
                throw new Exception(
                    "ERROR: expected a SignatureException but none was thrown"
                    + " and invalid signature was verified");
            } else {
                System.out.println("OK: verification failed as expected");
            }
        } else {
            throw new Exception(
                "ERROR: expected a SignatureException but none was thrown");
        }
    } catch (SignatureException e) {
        System.out.println("OK: caught expected exception: " + e);
    }
    System.out.println();
}
 
Example 19
Source File: X509CRLImpl.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Encodes an X.509 CRL, and signs it using the given key.
 *
 * @param key the private key used for signing.
 * @param algorithm the name of the signature algorithm used.
 * @param provider the name of the provider.
 *
 * @exception NoSuchAlgorithmException on unsupported signature
 * algorithms.
 * @exception InvalidKeyException on incorrect key.
 * @exception NoSuchProviderException on incorrect provider.
 * @exception SignatureException on signature errors.
 * @exception CRLException if any mandatory data was omitted.
 */
public void sign(PrivateKey key, String algorithm, String provider)
throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
    NoSuchProviderException, SignatureException {
    try {
        if (readOnly)
            throw new CRLException("cannot over-write existing CRL");
        Signature sigEngine = null;
        if ((provider == null) || (provider.length() == 0))
            sigEngine = Signature.getInstance(algorithm);
        else
            sigEngine = Signature.getInstance(algorithm, provider);

        sigEngine.initSign(key);

                            // in case the name is reset
        sigAlgId = AlgorithmId.get(sigEngine.getAlgorithm());
        infoSigAlgId = sigAlgId;

        DerOutputStream out = new DerOutputStream();
        DerOutputStream tmp = new DerOutputStream();

        // encode crl info
        encodeInfo(tmp);

        // encode algorithm identifier
        sigAlgId.encode(tmp);

        // Create and encode the signature itself.
        sigEngine.update(tbsCertList, 0, tbsCertList.length);
        signature = sigEngine.sign();
        tmp.putBitString(signature);

        // Wrap the signed data in a SEQUENCE { data, algorithm, sig }
        out.write(DerValue.tag_Sequence, tmp);
        signedCRL = out.toByteArray();
        readOnly = true;

    } catch (IOException e) {
        throw new CRLException("Error while encoding data: " +
                               e.getMessage());
    }
}
 
Example 20
Source File: CertSigner.java    From MaxKey with Apache License 2.0 3 votes vote down vote up
/**
 * <p>
 * 生成数据签名
 * </p>
 * 
 * @param data 源数�?
 * @param keyStorePath 密钥库存储路�?
 * @param alias x509Certificate alias
 * @param password 密钥库密�?
 * @return
 * @throws Exception
 */
public static byte[] sign(byte[] data, KeyStore keyStore, String alias, String password) throws Exception {
    // 获得证书
    X509Certificate x509Certificate = (X509Certificate) KeyStoreUtil.getCertificate(keyStore, alias, password);
    // 取得私钥
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
    // 构建签名
    Signature signature = Signature.getInstance(x509Certificate.getSigAlgName());
    signature.initSign(privateKey);
    signature.update(data);
    return signature.sign();
}