當前位置: 首頁>>代碼示例>>Java>>正文


Java Signature.getInstance方法代碼示例

本文整理匯總了Java中java.security.Signature.getInstance方法的典型用法代碼示例。如果您正苦於以下問題:Java Signature.getInstance方法的具體用法?Java Signature.getInstance怎麽用?Java Signature.getInstance使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.security.Signature的用法示例。


在下文中一共展示了Signature.getInstance方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: main

import java.security.Signature; //導入方法依賴的package包/類
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");
        }
    }
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:41,代碼來源:NonStandardNames.java

示例2: sign

import java.security.Signature; //導入方法依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:30,代碼來源:SigningUtil.java

示例3: verifyKeyBlock

import java.security.Signature; //導入方法依賴的package包/類
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 );
	}
}
 
開發者ID:BiglySoftware,項目名稱:BiglyBT,代碼行數:25,代碼來源:DHTPluginStorageManager.java

示例4: verify

import java.security.Signature; //導入方法依賴的package包/類
/**
 * 校驗數字簽名
 * 
 * @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));
}
 
開發者ID:wooui,項目名稱:springboot-training,代碼行數:36,代碼來源:RSACoder.java

示例5: engineInitVerify

import java.security.Signature; //導入方法依賴的package包/類
/**
 * @inheritDoc
 */
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
    if (!(publicKey instanceof PublicKey)) {
        String supplied = publicKey.getClass().getName();
        String needed = PublicKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.signatureAlgorithm.initVerify((PublicKey) publicKey);
    } catch (InvalidKeyException ex) {
        // reinstantiate Signature object to work around bug in JDK
        // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
        Signature sig = this.signatureAlgorithm;
        try {
            this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
        } catch (Exception e) {
            // this shouldn't occur, but if it does, restore previous
            // Signature
            if (log.isLoggable(java.util.logging.Level.FINE)) {
                log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
            }
            this.signatureAlgorithm = sig;
        }
        throw new XMLSignatureException("empty", ex);
    }
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:32,代碼來源:SignatureDSA.java

示例6: verify

import java.security.Signature; //導入方法依賴的package包/類
private boolean verify(byte[] signature, byte[] message)
        throws GeneralSecurityException {
    if (publicKey == null) {
        throw new IllegalStateException("need to set public key with " +
                                        " OAuthConsumer.setProperty when " +
                                        "verifying RSA-SHA1 signatures.");
    }
    Signature verifier = Signature.getInstance("SHA1withRSA");
    verifier.initVerify(publicKey);
    verifier.update(message);
    return verifier.verify(signature);
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:13,代碼來源:RSA_SHA1.java

示例7: verify

import java.security.Signature; //導入方法依賴的package包/類
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");
    }
}
 
開發者ID:Appdome,項目名稱:ipack,代碼行數:32,代碼來源:X509V2AttributeCertificate.java

示例8: signBySoft256

import java.security.Signature; //導入方法依賴的package包/類
/**
 * @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;
}
 
開發者ID:Javen205,項目名稱:IJPay,代碼行數:16,代碼來源:SecureUtil.java

示例9: sign

import java.security.Signature; //導入方法依賴的package包/類
/**
 * 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);
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:12,代碼來源:RSAUtils.java

示例10: sign

import java.security.Signature; //導入方法依賴的package包/類
/**
 * <p>
 * 用私鑰對信息生成數字簽名
 * </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());
}
 
開發者ID:angcyo,項目名稱:RLibrary,代碼行數:21,代碼來源:RSAUtils.java

示例11: getRawInstance

import java.security.Signature; //導入方法依賴的package包/類
public static Signature getRawInstance(final String provider) throws NoSuchProviderException {
    try {
        return Signature.getInstance(RAW_ALGORITHM, provider);
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(rawAlgorithmAssertionMsg, ex);
    }
}
 
開發者ID:toshiapp,項目名稱:toshi-headless-client,代碼行數:8,代碼來源:ECSignatureFactory.java

示例12: getRawInstance

import java.security.Signature; //導入方法依賴的package包/類
public static Signature getRawInstance(final String provider) throws NoSuchProviderException {
  try {
    return Signature.getInstance(RAW_ALGORITHM, provider);
  } catch (NoSuchAlgorithmException ex) {
    throw new AssertionError(rawAlgorithmAssertionMsg, ex);
  }
}
 
開發者ID:Aptoide,項目名稱:AppCoins-ethereumj,代碼行數:8,代碼來源:ECSignatureFactory.java

示例13: engineInitVerify

import java.security.Signature; //導入方法依賴的package包/類
/** @inheritDoc */
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {

    if (!(publicKey instanceof PublicKey)) {
        String supplied = publicKey.getClass().getName();
        String needed = PublicKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.signatureAlgorithm.initVerify((PublicKey) publicKey);
    } catch (InvalidKeyException ex) {
        // reinstantiate Signature object to work around bug in JDK
        // see: http://bugs.java.com/view_bug.do?bug_id=4953555
        Signature sig = this.signatureAlgorithm;
        try {
            this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
        } catch (Exception e) {
            // this shouldn't occur, but if it does, restore previous
            // Signature
            if (log.isLoggable(java.util.logging.Level.FINE)) {
                log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
            }
            this.signatureAlgorithm = sig;
        }
        throw new XMLSignatureException("empty", ex);
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:31,代碼來源:SignatureECDSA.java

示例14: getUserSig

import java.security.Signature; //導入方法依賴的package包/類
@Override
public String getUserSig(String identifier, long expire)throws QCloudException {
	try {
		 	Security.addProvider(new BouncyCastleProvider());
	        Reader reader = new CharArrayReader(imConfig.getPrivateKey().toCharArray());
	        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
	        PEMParser parser = new PEMParser(reader);
	        Object obj = parser.readObject();
	        parser.close();
	    	PrivateKey privKeyStruct = converter.getPrivateKey((PrivateKeyInfo) obj);
			
			String jsonString = "{" 
			+ "\"TLS.account_type\":\"" + 0 +"\","
			+"\"TLS.identifier\":\"" + identifier +"\","
			+"\"TLS.appid_at_3rd\":\"" + 0 +"\","
		    +"\"TLS.sdk_appid\":\"" + imConfig.getSdkAppId() +"\","
			+"\"TLS.expire_after\":\"" + expire +"\","
	        +"\"TLS.version\": \"201512300000\""
			+"}";
			
			String time = String.valueOf(System.currentTimeMillis()/1000);
			String SerialString = 
				"TLS.appid_at_3rd:" + 0 + "\n" +
				"TLS.account_type:" + 0 + "\n" +
				"TLS.identifier:" + identifier + "\n" + 
				"TLS.sdk_appid:" + imConfig.getSdkAppId() + "\n" + 
				"TLS.time:" + time + "\n" +
				"TLS.expire_after:" + expire +"\n";
			
			//Create Signature by SerialString
			Signature signature = Signature.getInstance("SHA256withECDSA", "BC");
			signature.initSign(privKeyStruct);
			signature.update(SerialString.getBytes(Charset.forName("UTF-8")));
			byte[] signatureBytes = signature.sign();
			
			String sigTLS = Base64.encodeBase64String(signatureBytes);
			
			//Add TlsSig to jsonString
		    JSONObject jsonObject= JSON.parseObject(jsonString);
		    jsonObject.put("TLS.sig", (Object)sigTLS);
		    jsonObject.put("TLS.time", (Object)time);
		    jsonString = jsonObject.toString();
		    
		    //compression
		    Deflater compresser = new Deflater();
		    compresser.setInput(jsonString.getBytes(Charset.forName("UTF-8")));

		    compresser.finish();
		    byte [] compressBytes = new byte [512];
		    int compressBytesLength = compresser.deflate(compressBytes);
		    compresser.end();
		    return new String(Base64Url.base64EncodeUrl(Arrays.copyOfRange(compressBytes,0,compressBytesLength)));
	}catch (Exception e) {
		throw new  QCloudException(e);
	}
}
 
開發者ID:51wakeup,項目名稱:wakeup-qcloud-sdk,代碼行數:57,代碼來源:DefaultQCloudClient.java

示例15: testWolfSignWolfVerify

import java.security.Signature; //導入方法依賴的package包/類
@Test
public void testWolfSignWolfVerify()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           SignatureException, InvalidKeyException,
           InvalidAlgorithmParameterException {

    String toSign = "Hello World";
    byte[] toSignBuf = toSign.getBytes();
    byte[] signature = null;

    for (int i = 0; i < wolfJCEAlgos.length; i++) {

        Signature signer =
            Signature.getInstance(wolfJCEAlgos[i], "wolfJCE");
        Signature verifier =
            Signature.getInstance(wolfJCEAlgos[i], "wolfJCE");

        assertNotNull(signer);
        assertNotNull(verifier);

        SecureRandom rand =
            SecureRandom.getInstance("HashDRBG", "wolfJCE");
        assertNotNull(rand);

        /* generate key pair */
        KeyPair pair = generateKeyPair(wolfJCEAlgos[i], rand);
        assertNotNull(pair);

        PrivateKey priv = pair.getPrivate();
        PublicKey  pub  = pair.getPublic();

        /* generate signature */
        signer.initSign(priv);
        signer.update(toSignBuf, 0, toSignBuf.length);
        signature = signer.sign();

        /* verify signature */
        verifier.initVerify(pub);
        verifier.update(toSignBuf, 0, toSignBuf.length);
        boolean verified = verifier.verify(signature);

        if (verified != true) {
            fail("Signature verification failed when generating with " +
                    "wolfJCE and verifying with system default JCE " +
                    "provider");
        }
    }
}
 
開發者ID:wolfSSL,項目名稱:wolfcrypt-jni,代碼行數:49,代碼來源:WolfCryptSignatureTest.java


注:本文中的java.security.Signature.getInstance方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。