本文整理匯總了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;
}
示例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");
}
}
示例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());
}
}
示例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);
}
示例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);
}
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
}
示例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);
}
});
}
示例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);
}
示例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);
}
}
示例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);
}
示例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);
}
示例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);
}
}