Java 类java.security.Signature 实例源码

项目:openjdk-jdk10    文件:TestECDSA.java   
private static void verify(Provider provider, String alg, PublicKey key,
        byte[] data, byte[] sig, boolean result) throws Exception {
    Signature s = Signature.getInstance(alg, provider);
    s.initVerify(key);
    boolean r;
    s.update(data);
    r = s.verify(sig);
    if (r != result) {
        throw new Exception("Result mismatch, actual: " + r);
    }
    s.update(data);
    r = s.verify(sig);
    if (r != result) {
        throw new Exception("Result mismatch, actual: " + r);
    }
    System.out.println("Passed");
}
项目:PACE    文件:ValueSignerTest.java   
private void signatureTest(ValueSigner signer, KeyPairGenerator generator) throws Exception {
  byte[] data = "HELLO".getBytes();
  Signature signature = signer.getInstance(null);
  KeyPair pair = generator.generateKeyPair();

  signature.initSign(pair.getPrivate());
  signature.update(data);
  byte[] digest = signature.sign();

  assertThat("digest has a value", TestUtils.wrap(digest), is(not(emptyArray())));

  signature.initVerify(pair.getPublic());
  signature.update(data);
  assertThat("verification succeeds", signature.verify(digest), is(true));

  switch (signer) {
    case RSA_PKCS1:
      break;

    default:
      signature.initSign(pair.getPrivate());
      signature.update(data);
      assertThat("signatures correctly use random padding", signature.sign(), not(equalTo(digest)));
  }
}
项目:lams    文件:SigningUtil.java   
/**
 * Compute the raw signature value over the supplied input.
 * 
 * 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
 */
public static byte[] sign(PrivateKey signingKey, String jcaAlgorithmID, byte[] input) throws SecurityException {
    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: {}", new String(Hex.encode(rawSignature)));
        return rawSignature;
    } catch (GeneralSecurityException e) {
        log.error("Error during signature generation", e);
        throw new SecurityException("Error during signature generation", e);
    }
}
项目:springboot-training    文件:RSACoder.java   
/**
 * 用私钥对信息生成数字签名
 * 
 * @param data
 *            加密数据
 * @param privateKey
 *            私钥
 * 
 * @return
 * @throws Exception
 */
public static String sign(byte[] data, String privateKey) throws Exception {
    // 解密由base64编码的私钥
    byte[] keyBytes = decryptBASE64(privateKey);

    // 构造PKCS8EncodedKeySpec对象
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

    // KEY_ALGORITHM 指定的加密算法
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    // 取私钥匙对象
    PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);

    // 用私钥对信息生成数字签名
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(priKey);
    signature.update(data);

    return encryptBASE64(signature.sign());
}
项目:AppCoins-ethereumj    文件:ECKey.java   
/**
 * Signs the given hash and returns the R and S components as BigIntegers
 * and put them in ECDSASignature
 *
 * @param input to sign
 * @return ECDSASignature signature that contains the R and S components
 */
public ECDSASignature doSign(byte[] input) {
    if (input.length != 32) {
        throw new IllegalArgumentException("Expected 32 byte input to ECDSA signature, not " + input.length);
    }
    // No decryption of private key required.
    if (privKey == null)
        throw new MissingPrivateKeyException();
    if (privKey instanceof BCECPrivateKey) {
        ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
        ECPrivateKeyParameters privKeyParams = new ECPrivateKeyParameters(((BCECPrivateKey) privKey).getD(), CURVE);
        signer.init(true, privKeyParams);
        BigInteger[] components = signer.generateSignature(input);
        return new ECDSASignature(components[0], components[1]).toCanonicalised();
    } else {
        try {
            final Signature ecSig = ECSignatureFactory.getRawInstance(provider);
            ecSig.initSign(privKey);
            ecSig.update(input);
            final byte[] derSignature = ecSig.sign();
            return ECDSASignature.decodeFromDER(derSignature).toCanonicalised();
        } catch (SignatureException | InvalidKeyException ex) {
            throw new RuntimeException("ECKey signing error", ex);
        }
    }
}
项目:openjdk-jdk10    文件:TestSignatures.java   
private static void testSignature(String algorithm, PrivateKey privateKey,
        PublicKey publicKey) throws Exception {
    System.out.println("Testing " + algorithm + "...");
    Signature s = Signature.getInstance(algorithm, provider);
    s.initSign(privateKey);
    s.update(data);
    byte[] sig = s.sign();
    s.initVerify(publicKey);
    s.update(data);
    boolean result;
    result = s.verify(sig);
    if (result == false) {
        throw new Exception("Verification 1 failed");
    }
    s.update(data);
    result = s.verify(sig);
    if (result == false) {
        throw new Exception("Verification 2 failed");
    }
    result = s.verify(sig);
    if (result == true) {
        throw new Exception("Verification 3 succeeded");
    }
}
项目:BiglyBT    文件:DHTPluginStorageManager.java   
public static boolean
verifyKeyBlock(
    byte[]      request,
    byte[]      signature )
{
    try{
        Signature   verifier = Signature.getInstance("MD5withRSA" );

        verifier.initVerify( key_block_public_key );

        verifier.update( request );

        if ( !verifier.verify( signature )){

            return( false );
        }

        return( true );

    }catch( Throwable e ){

        return( false );
    }
}
项目:springboot-training    文件:RSACoder.java   
/**
 * 校验数字签名
 * 
 * @param data
 *            加密数据
 * @param publicKey
 *            公钥
 * @param sign
 *            数字签名
 * 
 * @return 校验成功返回true 失败返回false
 * @throws Exception
 * 
 */
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {

    // 解密由base64编码的公钥
    byte[] keyBytes = decryptBASE64(publicKey);

    // 构造X509EncodedKeySpec对象
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);

    // KEY_ALGORITHM 指定的加密算法
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    // 取公钥匙对象
    PublicKey pubKey = keyFactory.generatePublic(keySpec);

    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initVerify(pubKey);
    signature.update(data);

    // 验证签名是否正常
    return signature.verify(decryptBASE64(sign));
}
项目:automat    文件:RSACoder.java   
/**
 * 签名
 * 
 * @param data 待签名数据
 * @param privateKey 私钥
 * @return byte[] 数字签名
 * @throws Exception
 */
public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {
    // 转换私钥材料
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
    // 实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // 取私钥匙对象
    PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
    // 实例化Signature
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    // 初始化Signature
    signature.initSign(priKey);
    // 更新
    signature.update(data);
    // 签名
    return signature.sign();
}
项目:oauth-filter-for-java    文件:AbstractJwtValidator.java   
private boolean verifySignature(byte[] signingInput, byte[] signature, PublicKey publicKey)
{
    try
    {
        Signature verifier = Signature.getInstance("SHA256withRSA");

        verifier.initVerify(publicKey);
        verifier.update(signingInput);

        return verifier.verify(signature);
    }
    catch (Exception e)
    {
        throw new RuntimeException("Unable to validate JWT signature", e);
    }
}
项目:generator-thundr-gae-react    文件:GoogleCloudStorageJsonApiClient.java   
private byte[] sign(byte[] data) {
    byte[] signature;
    if (Environment.is(Environment.DEV)) {
        try {
            Signature rsa = Signature.getInstance("SHA256withRSA");
            rsa.initSign(gcsCredential.getServiceAccountPrivateKey());
            rsa.update(data);
            signature = rsa.sign();
        } catch (Exception e) {
            throw new GoogleCloudStorageException(e, "Error signing URL: %s", e.getMessage());
        }
    } else {
        AppIdentityService.SigningResult signingResult = appIdentityService.signForApp(data);
        signature = signingResult.getSignature();
    }
    return signature;
}
项目:IJPay    文件:SecureUtil.java   
/**
 * @param privateKey
 * @param data
 * @return
 * @throws Exception
 */
public static byte[] signBySoft256(PrivateKey privateKey, byte[] data)
        throws Exception {
    byte[] result = null;
    Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA256RSA, "BC");
    st.initSign(privateKey);
    st.update(data);
    result = st.sign();
    return result;
}
项目:incubator-servicecomb-java-chassis    文件:RSAUtils.java   
/**
 * if has performance problem ,change Signature to ThreadLocal instance 
 */
public static String sign(String content, PrivateKey privateKey)
    throws NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, InvalidKeyException {
  Signature signature = Signature.getInstance(SIGN_ALG);
  signature.initSign(privateKey);
  signature.update(content.getBytes());
  byte[] signByte = signature.sign();
  return encoder.encodeToString(signByte);
}
项目:incubator-servicecomb-java-chassis    文件:RSAUtils.java   
/**
 * 
 * if has performance problem ,change Signature to ThreadLocal instance  
 * @param publicKey public key after base64 encode 
 * @param sign 签名
 * @param content original content 
 * @return verify result
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public static boolean verify(String publicKey, String sign, String content)
    throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
  if (null == kf) {
    throw new NoSuchAlgorithmException(RSA_ALG + " KeyFactory not available");
  }
  byte[] bytes = decoder.decode(publicKey);
  X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
  PublicKey pubKey = kf.generatePublic(keySpec);
  Signature signature = Signature.getInstance(SIGN_ALG);
  signature.initVerify(pubKey);
  signature.update(content.getBytes());
  return signature.verify(decoder.decode(sign));
}
项目:nutz-pay    文件:SecureUtil.java   
/**
 * @param privateKey
 * @param data
 * @return
 * @throws Exception
 */
public static byte[] signBySoft(PrivateKey privateKey, byte[] data)
        throws Exception {
    byte[] result = null;
    Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA1RSA, "BC");
    st.initSign(privateKey);
    st.update(data);
    result = st.sign();
    return result;
}
项目:lams    文件:RSA_SHA1.java   
private byte[] sign(byte[] message) throws GeneralSecurityException {
    if (privateKey == null) {
        throw new IllegalStateException("need to set private key with " +
                                        "OAuthConsumer.setProperty when " +
                                        "generating RSA-SHA1 signatures.");
    }
    Signature signer = Signature.getInstance("SHA1withRSA");
    signer.initSign(privateKey);
    signer.update(message);
    return signer.sign();
}
项目:lams    文件:SigningUtil.java   
/**
 * Verify the signature value computed over the supplied input against the supplied signature value.
 * 
 * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of verification key
 * supplied.
 * 
 * @param verificationKey the key with which to compute and verify the signature
 * @param jcaAlgorithmID the Java JCA algorithm ID to use
 * @param signature the computed signature value received from the signer
 * @param input the input over which the signature is computed and verified
 * @return true if the signature value computed over the input using the supplied key and algorithm ID is identical
 *         to the supplied signature value
 * @throws SecurityException thrown if the signature computation or verification process results in an error
 */
public static boolean verify(PublicKey verificationKey, String jcaAlgorithmID, byte[] signature, byte[] input)
        throws SecurityException {
    Logger log = getLogger();

    log.debug("Verifying signature over input using public key of type {} and JCA algorithm ID {}", verificationKey
            .getAlgorithm(), jcaAlgorithmID);

    try {
        Signature sig = Signature.getInstance(jcaAlgorithmID);
        sig.initVerify(verificationKey);
        sig.update(input);
        return sig.verify(signature);
    } catch (GeneralSecurityException e) {
        log.error("Error during signature verification", e);
        throw new SecurityException("Error during signature verification", e);
    }
}
项目:jdk8u-jdk    文件:X509CRLImpl.java   
/**
 * Verifies that this CRL was signed using the
 * private key that corresponds to the given public key,
 * and that the signature verification was computed by
 * the given provider.
 *
 * @param key the PublicKey used to carry out the verification.
 * @param sigProvider the name of the signature provider.
 *
 * @exception NoSuchAlgorithmException on unsupported signature
 * algorithms.
 * @exception InvalidKeyException on incorrect key.
 * @exception NoSuchProviderException on incorrect provider.
 * @exception SignatureException on signature errors.
 * @exception CRLException on encoding errors.
 */
public synchronized void verify(PublicKey key, String sigProvider)
        throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
        NoSuchProviderException, SignatureException {

    if (sigProvider == null) {
        sigProvider = "";
    }
    if ((verifiedPublicKey != null) && verifiedPublicKey.equals(key)) {
        // this CRL has already been successfully verified using
        // this public key. Make sure providers match, too.
        if (sigProvider.equals(verifiedProvider)) {
            return;
        }
    }
    if (signedCRL == null) {
        throw new CRLException("Uninitialized CRL");
    }
    Signature   sigVerf = null;
    if (sigProvider.length() == 0) {
        sigVerf = Signature.getInstance(sigAlgId.getName());
    } else {
        sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider);
    }
    sigVerf.initVerify(key);

    if (tbsCertList == null) {
        throw new CRLException("Uninitialized CRL");
    }

    sigVerf.update(tbsCertList, 0, tbsCertList.length);

    if (!sigVerf.verify(signature)) {
        throw new SignatureException("Signature does not match.");
    }
    verifiedPublicKey = key;
    verifiedProvider = sigProvider;
}
项目:JAVA-    文件:RSACoder.java   
/**
 * 签名
 * 
 * @param data 待签名数据
 * @param privateKey 私钥
 * @return byte[] 数字签名
 * @throws Exception
 */
public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {
    // 转换私钥材料
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
    // 实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // 取私钥匙对象
    PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
    // 实例化Signature
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    // 初始化Signature
    signature.initSign(priKey);
    // 更新
    signature.update(data);
    // 签名
    return signature.sign();
}
项目:iBase4J    文件:RSACoder.java   
/**
 * 签名
 * 
 * @param data 待签名数据
 * @param privateKey 私钥
 * @return byte[] 数字签名
 * @throws Exception
 */
public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {
    // 转换私钥材料
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
    // 实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // 取私钥匙对象
    PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
    // 实例化Signature
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    // 初始化Signature
    signature.initSign(priKey);
    // 更新
    signature.update(data);
    // 签名
    return signature.sign();
}
项目:ipack    文件:X509V2AttributeCertificate.java   
public final void verify(
        PublicKey   key,
        String      provider)
        throws CertificateException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchProviderException, SignatureException
{
    Signature   signature = null;

    if (!cert.getSignatureAlgorithm().equals(cert.getAcinfo().getSignature()))
    {
        throw new CertificateException("Signature algorithm in certificate info not same as outer certificate");
    }

    signature = Signature.getInstance(cert.getSignatureAlgorithm().getObjectId().getId(), provider);

    signature.initVerify(key);

    try
    {
        signature.update(cert.getAcinfo().getEncoded());
    }
    catch (IOException e)
    {
        throw new SignatureException("Exception encoding certificate info object");
    }

    if (!signature.verify(this.getSignature()))
    {
        throw new InvalidKeyException("Public key presented not for certificate signature");
    }
}
项目:ipack    文件:JcaContentVerifierProviderBuilder.java   
private SignatureOutputStream createSignatureStream(AlgorithmIdentifier algorithm, PublicKey publicKey)
    throws OperatorCreationException
{
    try
    {
        Signature sig = helper.createSignature(algorithm);

        sig.initVerify(publicKey);

        return new SignatureOutputStream(sig);
    }
    catch (GeneralSecurityException e)
    {
        throw new OperatorCreationException("exception on setup: " + e, e);
    }
}
项目:ipack    文件:JcaContentVerifierProviderBuilder.java   
private Signature createRawSig(AlgorithmIdentifier algorithm, PublicKey publicKey)
{
    Signature rawSig;
    try
    {
        rawSig = helper.createRawSignature(algorithm);

        if (rawSig != null)
        {
            rawSig.initVerify(publicKey);
        }
    }
    catch (Exception e)
    {
        rawSig = null;
    }
    return rawSig;
}
项目:openjdk-jdk10    文件:X509CRLImpl.java   
/**
 * Verifies that this CRL was signed using the
 * private key that corresponds to the given public key,
 * and that the signature verification was computed by
 * the given provider. Note that the specified Provider object
 * does not have to be registered in the provider list.
 *
 * @param key the PublicKey used to carry out the verification.
 * @param sigProvider the signature provider.
 *
 * @exception NoSuchAlgorithmException on unsupported signature
 * algorithms.
 * @exception InvalidKeyException on incorrect key.
 * @exception SignatureException on signature errors.
 * @exception CRLException on encoding errors.
 */
public synchronized void verify(PublicKey key, Provider sigProvider)
        throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
        SignatureException {

    if (signedCRL == null) {
        throw new CRLException("Uninitialized CRL");
    }
    Signature sigVerf = null;
    if (sigProvider == null) {
        sigVerf = Signature.getInstance(sigAlgId.getName());
    } else {
        sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider);
    }
    sigVerf.initVerify(key);

    if (tbsCertList == null) {
        throw new CRLException("Uninitialized CRL");
    }

    sigVerf.update(tbsCertList, 0, tbsCertList.length);

    if (!sigVerf.verify(signature)) {
        throw new SignatureException("Signature does not match.");
    }
    verifiedPublicKey = key;
}
项目:ipack    文件:OperatorHelper.java   
public Signature createRawSignature(AlgorithmIdentifier algorithm)
{
    Signature   sig;

    try
    {
        String algName = getSignatureName(algorithm);

        algName = "NONE" + algName.substring(algName.indexOf("WITH"));

        sig = helper.createSignature(algName);

        // RFC 4056
        // When the id-RSASSA-PSS algorithm identifier is used for a signature,
        // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params.
        if (algorithm.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS))
        {
            AlgorithmParameters params = helper.createAlgorithmParameters(algName);

            params.init(algorithm.getParameters().toASN1Primitive().getEncoded(), "ASN.1");

            PSSParameterSpec spec = (PSSParameterSpec)params.getParameterSpec(PSSParameterSpec.class);
            sig.setParameter(spec);
        }
    }
    catch (Exception e)
    {
        return null;
    }

    return sig;
}
项目:ipack    文件:X509CertificateObject.java   
private void checkSignature(
    PublicKey key, 
    Signature signature) 
    throws CertificateException, NoSuchAlgorithmException, 
        SignatureException, InvalidKeyException
{
    if (!isAlgIdEqual(c.getSignatureAlgorithm(), c.getTBSCertificate().getSignature()))
    {
        throw new CertificateException("signature algorithm in TBS cert not same as outer cert");
    }

    ASN1Encodable params = c.getSignatureAlgorithm().getParameters();

    // TODO This should go after the initVerify?
    X509SignatureUtil.setSignatureParameters(signature, params);

    signature.initVerify(key);

    signature.update(this.getTBSCertificate());

    if (!signature.verify(this.getSignature()))
    {
        throw new SignatureException("certificate does not verify with supplied key");
    }
}
项目:ipack    文件:X509CRLObject.java   
public void verify(PublicKey key, String sigProvider)
    throws CRLException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchProviderException, SignatureException
{
    if (!c.getSignatureAlgorithm().equals(c.getTBSCertList().getSignature()))
    {
        throw new CRLException("Signature algorithm on CertificateList does not match TBSCertList.");
    }

    Signature sig;

    if (sigProvider != null)
    {
        sig = Signature.getInstance(getSigAlgName(), sigProvider);
    }
    else
    {
        sig = Signature.getInstance(getSigAlgName());
    }

    sig.initVerify(key);
    sig.update(this.getTBSCertList());

    if (!sig.verify(this.getSignature()))
    {
        throw new SignatureException("CRL does not verify with supplied public key.");
    }
}
项目:iBase4J    文件:RSACoder.java   
/**
 * 校验
 * 
 * @param data 待校验数据
 * @param publicKey 公钥
 * @param sign 数字签名
 * @return boolean 校验成功返回true 失败返回false
 * @throws Exception
 */
public static boolean verify(byte[] data, byte[] publicKey, byte[] sign) throws Exception {
    // 转换公钥材料
    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);
}
项目:jdk8u-jdk    文件:VerifyRangeCheckOverflow.java   
public static void main(String[] args) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
    keyPairGenerator.initialize(1024);
    KeyPair keys = keyPairGenerator.generateKeyPair();
    PublicKey publicKey = keys.getPublic();
    byte[] sigBytes = new byte[100];

    Signature signature = Signature.getInstance("SHA1withDSA");
    signature.initVerify(publicKey);
    try {
        signature.verify(sigBytes, Integer.MAX_VALUE, 1);
    } catch (IllegalArgumentException ex) {
        // Expected
    }
}
项目:jdk8u-jdk    文件:TestSignatureOidHelper.java   
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");
    }
}
项目:godlibrary    文件:RSAUtlis.java   
/**
 * 用私钥对信息生成数字签名
 *
 * @param data       //加密数据
 * @param privateKey //私钥
 * @return
 * @throws Exception
 */
public static String sign(byte[] data, String privateKey) throws Exception {
    // 解密私钥
    byte[] keyBytes = Base64.decode(privateKey.getBytes(), Base64.DEFAULT);
    // 构造PKCS8EncodedKeySpec对象
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
            keyBytes);
    // 指定加密算法
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // 取私钥匙对象
    PrivateKey privateKey2 = keyFactory
            .generatePrivate(pkcs8EncodedKeySpec);
    // 用私钥对信息生成数字签名
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(privateKey2);
    signature.update(data);
    return Base64.encodeToString(signature.sign(), Base64.DEFAULT);
}
项目:javaide    文件:SignedJarBuilder.java   
/** Write the certificate file with a digital signature. */
private void writeSignatureBlock(Signature signature, X509Certificate publicKey,
        PrivateKey privateKey)
        throws IOException, GeneralSecurityException {
    SignerInfo signerInfo = new SignerInfo(
            new X500Name(publicKey.getIssuerX500Principal().getName()),
            publicKey.getSerialNumber(),
            AlgorithmId.get(DIGEST_ALGORITHM),
            AlgorithmId.get(privateKey.getAlgorithm()),
            signature.sign());

    PKCS7 pkcs7 = new PKCS7(
            new AlgorithmId[] { AlgorithmId.get(DIGEST_ALGORITHM) },
            new ContentInfo(ContentInfo.DATA_OID, null),
            new X509Certificate[] { publicKey },
            new SignerInfo[] { signerInfo });

    pkcs7.encodeSignedData(mOutputJar);
}
项目:quilt    文件:RsaSha256Fulfillment.java   
@Override
public boolean verify(final RsaSha256Condition condition, final byte[] message) {
  Objects.requireNonNull(condition,
      "Can't verify a RsaSha256Fulfillment against an null condition.");
  Objects.requireNonNull(message, "Message must not be null!");

  if (!getCondition().equals(condition)) {
    return false;
  }

  try {
    Signature rsaSigner = Signature.getInstance(SHA_256_WITH_RSA_PSS);
    rsaSigner.initVerify(publicKey);
    rsaSigner.update(message);
    return rsaSigner.verify(signature);
  } catch (InvalidKeyException | NoSuchAlgorithmException | SignatureException e) {
    throw new RuntimeException(e);
  }
}
项目:PackageSigner2    文件:Signer.java   
/** Write a .RSA file with a digital signature. */
private static void signatureBlock(
        Signature signature,
        X509Certificate publicKey,
        OutputStream out)
        throws IOException, GeneralSecurityException {
    SignerInfo signerInfo = new SignerInfo(
            new X500Name(publicKey.getIssuerX500Principal().getName()),
            publicKey.getSerialNumber(),
            AlgorithmId.get("SHA1"),
            AlgorithmId.get("RSA"),
            signature.sign());

    PKCS7 pkcs7 = new PKCS7(
            new AlgorithmId[] { AlgorithmId.get("SHA1") },
            new ContentInfo(ContentInfo.DATA_OID, null),
            new X509Certificate[] { publicKey },
            new SignerInfo[] { signerInfo });

    System.out.print("\rGenerating signature block...");

    pkcs7.encodeSignedData(out);
}
项目:bigchaindb-java-driver    文件:RsaSha256Fulfillment.java   
public static RsaSha256Fulfillment BuildFromSecrets(String PEMEncodedPrivateKey, byte[] message, SecureRandom saltRandom) {
        ConditionType type = ConditionType.RSA_SHA256;

        try {
//            privKey = (RSAPrivateKeySpec)kf.generatePrivate(new PKCS8EncodedKeySpec(privateKey.payload));
            RSAPrivateKeySpec privKeySpec = RsaSha256Fulfillment.parsePEMEncodedPrivateKey(PEMEncodedPrivateKey);
            PrivateKey privKey = kf.generatePrivate(privKeySpec);
            Signature signatureEngine = RsaSha256Fulfillment.getSignEngine();
            signatureEngine.initSign(privKey /*, saltRandom */);
            signatureEngine.update(message);
            byte[] signature =  signatureEngine.sign();
            BigInteger modulus = privKeySpec.getModulus();
            FulfillmentPayload payload = RsaSha256Fulfillment.calculatePayload(modulus, signature);

            return new RsaSha256Fulfillment(type, payload, modulus, new SignaturePayload(signature));
        } catch (Exception e) {
            throw new RuntimeException(e.toString(), e);
        }
    }
项目:yggdrasil-mock    文件:PropertiesUtils.java   
private static String sign(String data) {
    try {
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(key, new SecureRandom());
        signature.update(data.getBytes(UTF_8));
        return Base64.getEncoder().encodeToString(signature.sign());
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}
项目:GitHub    文件:Codec.java   
/**
 * 校验数字签名
 *
 * @param data      加密数据
 * @param publicKey 公钥
 * @param sign      数字签名
 * @return
 * @throws Exception
 */
public static boolean verify(byte[] data, String publicKey, String sign)
        throws Exception {

    byte[] keyBytes = BASE64.decode(publicKey); // 解密由base64编码的公钥
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  // 构造X509EncodedKeySpec对象
    KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());  // KEY_ALGORITHM 指定的加密算法
    PublicKey pubKey = keyFactory.generatePublic(keySpec);   // 取公钥对象

    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initVerify(pubKey);
    signature.update(data);

    return signature.verify(BASE64.decode(sign));
}
项目:IJPay    文件:SecureUtil.java   
/**
 * 
 * @param privateKey
 * @param data
 * @return
 * @throws Exception
 */
public static byte[] signBySoft(PrivateKey privateKey, byte[] data)
        throws Exception {
    byte[] result = null;
    Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA1RSA, "BC");
    st.initSign(privateKey);
    st.update(data);
    result = st.sign();
    return result;
}
项目:dice    文件:RandomOrgUtil.java   
/**
 * Checks the signature based on given pub key and raw data
 *
 * @param publicKey used to verify the signature
 * @param plainData the plain data to verify
 * @param signature as byte array
 * @return true if the signature can be verified with given data
 */
static boolean verifyRSA(PublicKey publicKey, byte[] plainData, byte[] signature) {
    try {
        Signature sig = Signature.getInstance("SHA512withRSA");
        sig.initVerify(publicKey);
        sig.update(plainData);
        return sig.verify(signature);
    } catch (Exception e) {
        throw new IllegalStateException("could not verify", e);
    }
}
项目:IJPay    文件:SecureUtil.java   
public static boolean validateSignBySoft256(PublicKey publicKey,
        byte[] signData, byte[] srcData) throws Exception {
    Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA256RSA, "BC");
    st.initVerify(publicKey);
    st.update(srcData);
    return st.verify(signData);
}