当前位置: 首页>>代码示例>>Java>>正文


Java PrivateKey类代码示例

本文整理汇总了Java中java.security.PrivateKey的典型用法代码示例。如果您正苦于以下问题:Java PrivateKey类的具体用法?Java PrivateKey怎么用?Java PrivateKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


PrivateKey类属于java.security包,在下文中一共展示了PrivateKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: loadPrivateKey

import java.security.PrivateKey; //导入依赖的package包/类
/**
 * Load a private key from a base64 encoded string
 * @param key The base64 encoded key
 * @return The private key
 */
public static PrivateKey loadPrivateKey(String key) {
    KeyFactory kf = getKeyFactory();
    if(kf == null) {
        return null;
    }

    byte[] rawKey = Base64.decode(key, Base64.DEFAULT);
    PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(rawKey);
    try {
        return kf.generatePrivate(ks);
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }
    return null;
}
 
开发者ID:wkmeijer,项目名称:CS4160-trustchain-android,代码行数:21,代码来源:Key.java

示例2: testSignature

import java.security.PrivateKey; //导入依赖的package包/类
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");
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:25,代码来源:TestSignatures.java

示例3: engineGeneratePrivate

import java.security.PrivateKey; //导入依赖的package包/类
/**
 * Generates a private key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the private key
 *
 * @return the private key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a private key.
 */
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
throws InvalidKeySpecException {
    try {
        if (keySpec instanceof DSAPrivateKeySpec) {
            DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec)keySpec;
            return new DSAPrivateKey(dsaPrivKeySpec.getX(),
                                     dsaPrivKeySpec.getP(),
                                     dsaPrivKeySpec.getQ(),
                                     dsaPrivKeySpec.getG());

        } else if (keySpec instanceof PKCS8EncodedKeySpec) {
            return new DSAPrivateKey
                (((PKCS8EncodedKeySpec)keySpec).getEncoded());

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification: " + e.getMessage());
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:35,代码来源:DSAKeyFactory.java

示例4: signZip

import java.security.PrivateKey; //导入依赖的package包/类
/** KeyStore-type agnostic.  This method will sign the zip file, automatically handling JKS or BKS keystores. */
public static void signZip( ZipSigner zipSigner,
                     String keystorePath,
                     char[] keystorePw,
                     String certAlias,
                     char[] certPw,
                     String signatureAlgorithm,
                     String inputZipFilename,
                     String outputZipFilename)
    throws Exception
{
    zipSigner.issueLoadingCertAndKeysProgressEvent();
    KeyStore keystore = KeyStoreFileManager.loadKeyStore( keystorePath, keystorePw);
    Certificate cert = keystore.getCertificate(certAlias);
    X509Certificate publicKey = (X509Certificate)cert;
    Key key = keystore.getKey(certAlias, certPw);
    PrivateKey privateKey = (PrivateKey)key;

    zipSigner.setKeys( "custom", publicKey, privateKey, signatureAlgorithm, null);
    zipSigner.signZip( inputZipFilename, outputZipFilename);
}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:22,代码来源:CustomKeySigner.java

示例5: engineInitSign

import java.security.PrivateKey; //导入依赖的package包/类
/** @inheritDoc */
protected void engineInitSign(Key privateKey) throws XMLSignatureException {
    if (!(privateKey instanceof PrivateKey)) {
        String supplied = privateKey.getClass().getName();
        String needed = PrivateKey.class.getName();
        Object exArgs[] = { supplied, needed };

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

    try {
        this.signatureAlgorithm.initSign((PrivateKey) privateKey);
    } catch (InvalidKeyException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:17,代码来源:SignatureBaseRSA.java

示例6: encrypt

import java.security.PrivateKey; //导入依赖的package包/类
public static String encrypt(byte[] keyBytes, String plainText)
		throws Exception {
	PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
	KeyFactory factory = KeyFactory.getInstance("RSA");
	PrivateKey privateKey = factory.generatePrivate(spec);
	Cipher cipher = Cipher.getInstance("RSA");
       try {
	    cipher.init(Cipher.ENCRYPT_MODE, privateKey);
       } catch (InvalidKeyException e) {
           //For IBM JDK, 原因请看解密方法中的说明
           RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
           RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
           Key fakePublicKey = KeyFactory.getInstance("RSA").generatePublic(publicKeySpec);
           cipher = Cipher.getInstance("RSA");
           cipher.init(Cipher.ENCRYPT_MODE, fakePublicKey);
       }

	byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
	String encryptedString = Base64.byteArrayToBase64(encryptedBytes);

	return encryptedString;
}
 
开发者ID:huang-up,项目名称:mycat-src-1.6.1-RELEASE,代码行数:23,代码来源:DecryptUtil.java

示例7: sign

import java.security.PrivateKey; //导入依赖的package包/类
/**
* RSA签名
* @param content 待签名数据
* @param privateKey 商户私钥
* @param input_charset 编码格式
* @return 签名值
*/
public static String sign(String content, String privateKey, String input_charset)
{
       try 
       {
       	PKCS8EncodedKeySpec priPKCS8 	= new PKCS8EncodedKeySpec( Base64.decode(privateKey) ); 
       	KeyFactory keyf 				= KeyFactory.getInstance("RSA");
       	PrivateKey priKey 				= keyf.generatePrivate(priPKCS8);

           java.security.Signature signature = java.security.Signature
               .getInstance(SIGN_ALGORITHMS);

           signature.initSign(priKey);
           signature.update( content.getBytes(input_charset) );

           byte[] signed = signature.sign();
           
           return Base64.encode(signed);
       }
       catch (Exception e) 
       {
       	e.printStackTrace();
       }
       
       return null;
   }
 
开发者ID:dianbaer,项目名称:epay,代码行数:33,代码来源:RSA.java

示例8: fetchPrivateKey

import java.security.PrivateKey; //导入依赖的package包/类
private PrivateKey fetchPrivateKey(Context context, String alias) throws KeyChainException,
        InterruptedException, MessagingException {

    PrivateKey privateKey = KeyChain.getPrivateKey(context, alias);
    if (privateKey == null) {
        throw new MessagingException("No private key found for: " + alias);
    }

    /*
     * We need to keep reference to the first private key retrieved so
     * it won't get garbage collected. If it will then the whole app
     * will crash on Android < 4.2 with "Fatal signal 11 code=1". See
     * https://code.google.com/p/android/issues/detail?id=62319
     */
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        savePrivateKeyReference(privateKey);
    }

    return privateKey;
}
 
开发者ID:philipwhiuk,项目名称:q-mail,代码行数:21,代码来源:KeyChainKeyManager.java

示例9: engineInitSign

import java.security.PrivateKey; //导入依赖的package包/类
/**
 * @inheritDoc
 */
protected void engineInitSign(Key privateKey) throws XMLSignatureException {
    if (!(privateKey instanceof PrivateKey)) {
        String supplied = privateKey.getClass().getName();
        String needed = PrivateKey.class.getName();
        Object exArgs[] = { supplied, needed };

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

    try {
        this.signatureAlgorithm.initSign((PrivateKey) privateKey);
    } catch (InvalidKeyException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:19,代码来源:SignatureDSA.java

示例10: printInfo

import java.security.PrivateKey; //导入依赖的package包/类
/**
 * This method prints the key chain information.
 */
private void printInfo() {
    String alias = getAlias();
    X509Certificate[] certs = getCertificateChain(alias);
    final PrivateKey privateKey = getPrivateKey(alias);
    final StringBuffer sb = new StringBuffer();
    for (X509Certificate cert : certs) {
        sb.append(cert.getIssuerDN());
        sb.append("\n");
    }
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            TextView certTv = (TextView) findViewById(R.id.cert);
            TextView privateKeyTv = (TextView) findViewById(R.id.private_key);
            certTv.setText(sb.toString());
            privateKeyTv.setText(privateKey.getFormat() + ":" + privateKey);
        }
    });
}
 
开发者ID:sdrausty,项目名称:buildAPKsSamples,代码行数:23,代码来源:KeyChainDemoActivity.java

示例11: testBadPrivateKey

import java.security.PrivateKey; //导入依赖的package包/类
@Test
public void testBadPrivateKey()  throws IOException, FileNotFoundException, ClassNotFoundException, 
        InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, 
        InstantiationException {
    // Let wallet and keyPairs be the wallet and the pair of keys associated to user's account
    // and stored on the hard drive.
    final KeyPair keyPair = createKeyPair();

    // Let's suppose that an attacker entered a bad password and thus, got a bad DSA private key from
    // the decryption algorithm.
    final PrivateKey badPrivateKey = Cryptography.generateKeyPair().getPrivate();

    // The offline software must check whether this key is wrong or not. Let's do this by signing a
    // test transaction (it can be anything, let's write random bytes) and verify the signature.
    final byte[] transaction = randomBytes(156);
    final byte[] badSignature = Cryptography.signData(badPrivateKey, transaction);
    assertEquals(Cryptography.verifySignature(keyPair.getPublic(), transaction, badSignature), false);
}
 
开发者ID:StanIsAdmin,项目名称:CrashCoin,代码行数:19,代码来源:TestWallet.java

示例12: engineInitSign

import java.security.PrivateKey; //导入依赖的package包/类
/** @inheritDoc */
protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
    throws XMLSignatureException {
    if (!(privateKey instanceof PrivateKey)) {
        String supplied = privateKey.getClass().getName();
        String needed = PrivateKey.class.getName();
        Object exArgs[] = { supplied, needed };

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

    try {
        this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
    } catch (InvalidKeyException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:18,代码来源:SignatureECDSA.java

示例13: addKeyAgreementRecipients

import java.security.PrivateKey; //导入依赖的package包/类
/**
 * Add multiple key agreement based recipients (sharing a single KeyAgreeRecipientInfo structure).
 *
 * @deprecated use the addRecipientGenerator and JceKeyAgreeRecipientInfoGenerator
 * @param agreementAlgorithm key agreement algorithm to use.
 * @param senderPrivateKey private key to initialise sender side of agreement with.
 * @param senderPublicKey sender public key to include with message.
 * @param recipientCerts recipients' public key certificates.
 * @param cekWrapAlgorithm OID for key wrapping algorithm to use.
 * @param provider provider to use for the agreement calculation.
 * @exception NoSuchAlgorithmException if the algorithm requested cannot be found
 * @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
 */
public void addKeyAgreementRecipients(
    String           agreementAlgorithm,
    PrivateKey       senderPrivateKey,
    PublicKey        senderPublicKey,
    Collection       recipientCerts,
    String           cekWrapAlgorithm,
    Provider         provider)
    throws NoSuchAlgorithmException, InvalidKeyException
{
    JceKeyAgreeRecipientInfoGenerator recipientInfoGenerator = new JceKeyAgreeRecipientInfoGenerator(new ASN1ObjectIdentifier(agreementAlgorithm), senderPrivateKey, senderPublicKey, new ASN1ObjectIdentifier(cekWrapAlgorithm)).setProvider(provider);

    for (Iterator it = recipientCerts.iterator(); it.hasNext();)
    {
        try
        {
            recipientInfoGenerator.addRecipient((X509Certificate)it.next());
        }
        catch (CertificateEncodingException e)
        {
            throw new IllegalArgumentException("unable to encode certificate: " + e.getMessage());
        }
    }

    oldRecipientInfoGenerators.add(recipientInfoGenerator);
}
 
开发者ID:Appdome,项目名称:ipack,代码行数:39,代码来源:CMSEnvelopedGenerator.java

示例14: loadRsaKeys

import java.security.PrivateKey; //导入依赖的package包/类
private KeyPair loadRsaKeys(Path publicFile, Path privateFile)
	throws GeneralSecurityException, ReflectiveOperationException,
	IOException
{
	KeyFactory factory = KeyFactory.getInstance("RSA");
	
	// load public key
	PublicKey publicKey;
	try(ObjectInputStream in =
		new ObjectInputStream(Files.newInputStream(publicFile)))
	{
		publicKey = factory.generatePublic(new RSAPublicKeySpec(
			(BigInteger)in.readObject(), (BigInteger)in.readObject()));
	}
	
	// load private key
	PrivateKey privateKey;
	try(ObjectInputStream in =
		new ObjectInputStream(Files.newInputStream(privateFile)))
	{
		privateKey = factory.generatePrivate(new RSAPrivateKeySpec(
			(BigInteger)in.readObject(), (BigInteger)in.readObject()));
	}
	
	return new KeyPair(publicKey, privateKey);
}
 
开发者ID:Wurst-Imperium,项目名称:Wurst-MC-1.12,代码行数:27,代码来源:Encryption.java

示例15: rsa256Sign

import java.security.PrivateKey; //导入依赖的package包/类
public static String rsa256Sign(String content, String privateKey,
                                String charset) throws AlipayApiException {

    try {
        PrivateKey priKey = getPrivateKeyFromPKCS8(AlipayConstants.SIGN_TYPE_RSA,
            new ByteArrayInputStream(privateKey.getBytes()));

        java.security.Signature signature = java.security.Signature
            .getInstance(AlipayConstants.SIGN_SHA256RSA_ALGORITHMS);

        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));
    } catch (Exception e) {
        throw new AlipayApiException("RSAcontent = " + content + "; charset = " + charset, e);
    }

}
 
开发者ID:1991wangliang,项目名称:pay,代码行数:27,代码来源:AlipaySignature.java


注:本文中的java.security.PrivateKey类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。