本文整理汇总了Java中org.bouncycastle.openpgp.PGPPublicKeyRing.getPublicKey方法的典型用法代码示例。如果您正苦于以下问题:Java PGPPublicKeyRing.getPublicKey方法的具体用法?Java PGPPublicKeyRing.getPublicKey怎么用?Java PGPPublicKeyRing.getPublicKey使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.bouncycastle.openpgp.PGPPublicKeyRing
的用法示例。
在下文中一共展示了PGPPublicKeyRing.getPublicKey方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: removeSignature
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
public static PGPPublicKeyRing removeSignature( PGPPublicKeyRing keyToRemoveFrom, String id ) throws PGPException
{
try
{
PGPPublicKey oldKey = keyToRemoveFrom.getPublicKey();
PGPPublicKey newKey = PGPPublicKey.removeCertification( oldKey, id );
PGPPublicKeyRing newPublicKeyRing = PGPPublicKeyRing.removePublicKey( keyToRemoveFrom, oldKey );
return PGPPublicKeyRing.insertPublicKey( newPublicKeyRing, newKey );
}
catch ( Exception e )
{
//throw custom exception
throw new PGPException( "Error removing signature", e );
}
}
示例2: getPublicKeyId
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
@Override
public Response getPublicKeyId( final String identityId )
{
try
{
PGPPublicKeyRing pubRing = securityManager.getKeyManager().getPublicKeyRing( identityId );
PGPPublicKey key = pubRing.getPublicKey();
if ( key == null )
{
logger.info( " ************* Public Key not found with id:" + identityId );
return Response.status( Response.Status.NOT_FOUND ).entity( "Object Not found" ).build();
}
else
{
return Response.ok( PGPKeyUtil.encodeNumericKeyId( key.getKeyID() ) ).build();
}
}
catch ( Exception ex )
{
logger.info( " ************* Error ! Public Key not found with id:" + identityId, ex );
return Response.status( Response.Status.NOT_FOUND ).entity( "Object Not found" ).build();
}
}
示例3: rememberKey
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
/**
* Simply stores the key ID in {@link #discoveredKeyIds} for future
* reference of all Key IDs we've come across. This method uses a
* {@link PGPPublicKeyRing} to ensure the input is actually a valid key,
* plus locating any key IDs that have signed the key.
* <p>
* Please note {@link #discoveredKeyIds} is not used for any key functions
* of this class. It is simply for user interface convenience.
*
* @param keyRing the key ID to store (required)
*/
@SuppressWarnings("unchecked")
private void rememberKey(final PGPPublicKeyRing keyRing) {
final PGPPublicKey key = keyRing.getPublicKey();
if (key != null) {
final PgpKeyId keyId = new PgpKeyId(key);
discoveredKeyIds.add(keyId);
final Iterator<String> userIdIterator = key.getUserIDs();
while (userIdIterator.hasNext()) {
final String userId = userIdIterator.next();
final Iterator<PGPSignature> signatureIterator = key
.getSignaturesForID(userId);
while (signatureIterator.hasNext()) {
final PGPSignature signature = signatureIterator.next();
final PgpKeyId signatureKeyId = new PgpKeyId(signature);
discoveredKeyIds.add(signatureKeyId);
}
}
}
}
示例4: getPublicKeyWithKeyIdAndUserID
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
/**
* Determines a public key from the keyring collection which has a certain
* key ID and which has a User ID which contains at least one of the User ID
* parts.
*
* @param keyId
* key ID
* @param userIdParts
* user ID parts, can be empty, than no filter on the User ID is
* executed
* @param publicKeyringCollection
* keyring collection
* @return public key or <code>null</code> if no fitting key is found
* @throws PGPException
*/
@SuppressWarnings("unchecked")
public static PGPPublicKey getPublicKeyWithKeyIdAndUserID(long keyId, List<String> userIdParts, PGPPublicKeyRingCollection publicKeyringCollection)
throws PGPException {
PGPPublicKeyRing publicKeyring = publicKeyringCollection.getPublicKeyRing(keyId);
if (publicKeyring == null) {
LOG.debug("No public key found for key ID {}.", Long.toString(keyId));
return null;
}
// publicKey can be a subkey the user IDs must therefore be provided by the primary/master key
if (isAllowedKey(userIdParts, publicKeyring.getPublicKey().getUserIDs())) {
return publicKeyring.getPublicKey(keyId);
} else {
return null;
}
}
示例5: signPublicKey
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
/**
* Signs a public key
*
* @param publicKeyRing a public key ring containing the single public key to sign
* @param id the id we are certifying against the public key
* @param secretKey the signing key
* @param secretKeyPassword the signing key password
*
* @return a public key ring with the signed public key
*/
public static PGPPublicKeyRing signPublicKey( PGPPublicKeyRing publicKeyRing, String id, PGPSecretKey secretKey,
String secretKeyPassword ) throws PGPException
{
try
{
PGPPublicKey oldKey = publicKeyRing.getPublicKey();
PGPPrivateKey pgpPrivKey = secretKey.extractPrivateKey(
new JcePBESecretKeyDecryptorBuilder().setProvider( provider )
.build( secretKeyPassword.toCharArray() ) );
PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
new JcaPGPContentSignerBuilder( secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1 ) );
signatureGenerator.init( PGPSignature.DEFAULT_CERTIFICATION, pgpPrivKey );
PGPSignature signature = signatureGenerator.generateCertification( id, oldKey );
PGPPublicKey newKey = PGPPublicKey.addCertification( oldKey, signature );
PGPPublicKeyRing newPublicKeyRing = PGPPublicKeyRing.removePublicKey( publicKeyRing, oldKey );
return PGPPublicKeyRing.insertPublicKey( newPublicKeyRing, newKey );
}
catch ( Exception e )
{
//throw custom exception
throw new PGPException( "Error signing public key", e );
}
}
示例6: verifySignature
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
@Override
public boolean verifySignature( PGPPublicKeyRing sourcePubRing, PGPPublicKeyRing targetPubRing )
{
PGPPublicKey keyToVerifyWith = sourcePubRing.getPublicKey();
PGPPublicKey keyToVerify = targetPubRing.getPublicKey();
String sigId = PGPKeyUtil.encodeNumericKeyId( keyToVerify.getKeyID() );
return encryptionTool.verifyPublicKey( keyToVerify, sigId, keyToVerifyWith );
}
示例7: removeSignature
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
@Override
public PGPPublicKeyRing removeSignature( String sourceFingerprint, String targetFingerprint )
{
PGPPublicKeyRing targetPubRing = getPublicKeyRingByFingerprint( targetFingerprint );
PGPPublicKeyRing sourcePubRing = getPublicKeyRingByFingerprint( sourceFingerprint );
PGPPublicKey sourcePublicKey = sourcePubRing.getPublicKey();
return removeSignature( sourcePublicKey, targetPubRing );
}
示例8: fromArmored
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
public static BcPublicKey fromArmored(String armoredKeyString) throws PGPKeyInitialisationException {
try {
PGPPublicKeyRing pubKeyRing = new PGPPublicKeyRing(
new ArmoredInputStream(new ByteArrayInputStream(armoredKeyString.getBytes(StandardCharsets.UTF_8))),
new BcKeyFingerprintCalculator()
);
if (Iterators.size(pubKeyRing.getPublicKeys()) < 1) {
throw new PGPKeyInitialisationException("No keys in keyring");
}
PGPPublicKey signingKey = pubKeyRing.getPublicKey();
PGPPublicKey encryptionKey;
@SuppressWarnings("unchecked")
List<PGPPublicKey> keys = Lists.newArrayList(pubKeyRing.getPublicKeys());
if (keys.size() == 1) {
encryptionKey = signingKey;
} else {
encryptionKey = keys.get(1);
}
if (!encryptionKey.isEncryptionKey()) {
throw new PGPKeyInitialisationException("Error instatiating public key: sign-only key.");
}
return new BcPublicKey(signingKey, encryptionKey);
} catch (RuntimeException | IOException e) {
throw new PGPKeyInitialisationException("Error instantiating a public key", e);
}
}
示例9: testSignVerify_Detached
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
@Test
public void testSignVerify_Detached() throws Exception {
// Load the keys.
PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY);
PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY);
PGPPublicKey publicKey = publicKeyRing.getPublicKey();
PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey());
// Sign the data and write signature data to "signatureFile".
// Note: RSA_GENERAL will encrypt AND sign. RSA_SIGN and RSA_ENCRYPT are deprecated.
PGPSignatureGenerator signer = new PGPSignatureGenerator(
new BcPGPContentSignerBuilder(RSA_GENERAL, SHA256));
signer.init(PGPSignature.BINARY_DOCUMENT, privateKey);
addUserInfoToSignature(publicKey, signer);
signer.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
ByteArrayOutputStream output = new ByteArrayOutputStream();
signer.generate().encode(output);
byte[] signatureFileData = output.toByteArray();
logger.info(".sig file data: " + dumpHex(signatureFileData));
// Load algorithm information and signature data from "signatureFileData".
PGPSignature sig;
try (ByteArrayInputStream input = new ByteArrayInputStream(signatureFileData)) {
PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
PGPSignatureList sigList = (PGPSignatureList) pgpFact.nextObject();
assertThat(sigList.size()).isEqualTo(1);
sig = sigList.get(0);
}
// Use "onePass" and "sig" to verify "publicKey" signed the text.
sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
sig.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
assertThat(sig.verify()).isTrue();
// Verify that they DIDN'T sign the text "hello monster".
sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
sig.update("hello monster".getBytes(UTF_8));
assertThat(sig.verify()).isFalse();
}
示例10: testEncryptDecrypt_ExplicitStyle
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
@Test
public void testEncryptDecrypt_ExplicitStyle() throws Exception {
int bufferSize = 64 * 1024;
// Alice loads Bob's "publicKey" into memory.
PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY);
PGPPublicKey publicKey = publicKeyRing.getPublicKey();
// Alice encrypts the secret message for Bob using his "publicKey".
PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(
new BcPGPDataEncryptorBuilder(AES_128));
encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
byte[] encryptedData;
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
try (OutputStream output2 = encryptor.open(output, new byte[bufferSize])) {
output2.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
}
encryptedData = output.toByteArray();
}
logger.info("Encrypted data: " + dumpHex(encryptedData));
// Bob loads his "privateKey" into memory.
PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY);
PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey());
// Bob decrypt's the OpenPGP message (w/ ciphertext) using his "privateKey".
try (ByteArrayInputStream input = new ByteArrayInputStream(encryptedData)) {
PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
PGPEncryptedDataList encDataList = (PGPEncryptedDataList) pgpFact.nextObject();
assertThat(encDataList.size()).isEqualTo(1);
PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0);
assertThat(encData.getKeyID()).isEqualTo(publicKey.getKeyID());
assertThat(encData.getKeyID()).isEqualTo(privateKey.getKeyID());
try (InputStream original =
encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) {
assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8)))
.isEqualTo(FALL_OF_HYPERION_A_DREAM);
}
}
}
示例11: findPublicKeys
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
public static List<PGPPublicKey> findPublicKeys(List<String> useridParts, boolean forEncryption, PGPPublicKeyRingCollection pgpPublicKeyringCollection) {
List<PGPPublicKey> result = new ArrayList<PGPPublicKey>(useridParts.size());
for (Iterator<PGPPublicKeyRing> keyRingIter = pgpPublicKeyringCollection.getKeyRings(); keyRingIter.hasNext();) {
PGPPublicKeyRing keyRing = keyRingIter.next();
PGPPublicKey primaryKey = keyRing.getPublicKey();
String[] foundKeyUserIdForUserIdPart = findFirstKeyUserIdContainingOneOfTheParts(useridParts, primaryKey);
if (foundKeyUserIdForUserIdPart == null) {
LOG.debug("No User ID found in primary key with key ID {} containing one of the parts {}", primaryKey.getKeyID(),
useridParts);
continue;
}
LOG.debug("User ID {} found in primary key with key ID {} containing one of the parts {}", new Object[] {
foundKeyUserIdForUserIdPart[0], primaryKey.getKeyID(), useridParts });
// add adequate keys to the result
for (Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys(); keyIter.hasNext();) {
PGPPublicKey key = keyIter.next();
if (forEncryption) {
if (isEncryptionKey(key)) {
LOG.debug("Public encryption key with key user ID {} and key ID {} added to the encryption keys",
foundKeyUserIdForUserIdPart[0], Long.toString(key.getKeyID()));
result.add(key);
}
} else if (!forEncryption && isSignatureKey(key)) {
// not used!
result.add(key);
LOG.debug("Public key with key user ID {} and key ID {} added to the signing keys", foundKeyUserIdForUserIdPart[0],
Long.toString(key.getKeyID()));
}
}
}
return result;
}
示例12: exportKey
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
/**
* Export a GPG key (armored) from a GPG home directory to a filename
*
* @param gpgHomeDirectory GPG home directory where to look up the GPG key
* @param keyId GPG key to look up
* @param filename Filename to save the GPG key to
*
* @throws FileNotFoundException
* @throws IOException
* @throws PGPException
*/
static public void exportKey(String gpgHomeDirectory, String keyId, String filename) throws FileNotFoundException, IOException, PGPException {
FileInputStream in = new FileInputStream(gpgHomeDirectory + "/pubring.gpg");
Security.addProvider(new BouncyCastleProvider());
PGPPublicKeyRingCollection pubRings = new PGPPublicKeyRingCollection(in, new JcaKeyFingerprintCalculator());
Iterator rIt = pubRings.getKeyRings();
PGPPublicKey pubKey = null;
while (rIt.hasNext()) {
PGPPublicKeyRing pgpPub = (PGPPublicKeyRing) rIt.next();
try {
pubKey = pgpPub.getPublicKey();
} catch (Exception e) {
LOGGER.error(e);
continue;
}
Iterator it = pgpPub.getPublicKeys();
boolean firstKey = true;
while (it.hasNext()) {
PGPPublicKey pgpKey = (PGPPublicKey) it.next();
if (firstKey) {
String crtkeyid = Long.toHexString(pgpKey.getKeyID()).toUpperCase();
if (crtkeyid.equals(keyId)) {
ByteArrayOutputStream encOut = new ByteArrayOutputStream();
try (ArmoredOutputStream armorOut = new ArmoredOutputStream(encOut)) {
armorOut.write(pgpKey.getEncoded());
armorOut.flush();
}
try (FileOutputStream out = new FileOutputStream(new File(filename))) {
out.write(encOut.toByteArray());
out.flush();
}
}
firstKey = false;
}
}
}
try {
in.close();
} catch (IOException ex) {
LOGGER.error(ex);
}
}
示例13: parseKeyring
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
/**
* Read keyring and fetch keys and user ids
*
* @throws FileNotFoundException
* @throws IOException
* @throws PGPException
*/
private void parseKeyring() throws FileNotFoundException, IOException, PGPException {
// Reset the key table
this.gpgKeyData = new ArrayList<>();
// Read the keyring
FileInputStream in = new FileInputStream(this.gpgHomeDirectory + "/pubring.gpg");
Security.addProvider(new BouncyCastleProvider());
PGPPublicKeyRingCollection pubRings = new PGPPublicKeyRingCollection(in, new JcaKeyFingerprintCalculator());
Iterator rIt = pubRings.getKeyRings();
PGPPublicKey pubKey = null;
while (rIt.hasNext()) {
PGPPublicKeyRing pgpPub = (PGPPublicKeyRing) rIt.next();
try {
pubKey = pgpPub.getPublicKey();
} catch (Exception e) {
Logger.getLogger(GpgTableModel.class.getName()).log(Level.SEVERE, null, e);
continue;
}
Iterator it = pgpPub.getPublicKeys();
String userId = "unknown";
String keyId = "unkwown";
boolean firstKey = true;
boolean firstId = true;
while (it.hasNext()) {
PGPPublicKey pgpKey = (PGPPublicKey) it.next();
if (firstKey) {
keyId = Long.toHexString(pgpKey.getKeyID());
firstKey = false;
}
Iterator iid = pgpKey.getUserIDs();
while (iid.hasNext()) {
if (firstId) {
firstId = false;
userId = (String) iid.next();
} else {
iid.next();
}
}
}
this.gpgKeyData.add(new GpgTableModel.SimpleGpgKey(keyId, userId));
}
try {
in.close();
} catch (IOException ex) {
Logger.getLogger(GpgTableModel.class.getName()).log(Level.SEVERE, null, ex);
}
}
示例14: existingEmbeddedJpegTest
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
private void existingEmbeddedJpegTest()
throws Exception
{
PGPPublicKeyRing pgpPub = new PGPPublicKeyRing(embeddedJPEGKey, new BcKeyFingerprintCalculator());
PGPPublicKey pubKey = pgpPub.getPublicKey();
Iterator it = pubKey.getUserAttributes();
int count = 0;
while (it.hasNext())
{
PGPUserAttributeSubpacketVector attributes = (PGPUserAttributeSubpacketVector)it.next();
Iterator sigs = pubKey.getSignaturesForUserAttribute(attributes);
int sigCount = 0;
while (sigs.hasNext())
{
PGPSignature sig = (PGPSignature)sigs.next();
sig.init(new BcPGPContentVerifierBuilderProvider(), pubKey);
if (!sig.verifyCertification(attributes, pubKey))
{
fail("signature failed verification");
}
sigCount++;
}
if (sigCount != 1)
{
fail("Failed user attributes signature check");
}
count++;
}
if (count != 1)
{
fail("didn't find user attributes");
}
}
示例15: embeddedJpegTest
import org.bouncycastle.openpgp.PGPPublicKeyRing; //导入方法依赖的package包/类
private void embeddedJpegTest()
throws Exception
{
PGPPublicKeyRing pgpPub = new PGPPublicKeyRing(testPubKey, new BcKeyFingerprintCalculator());
PGPSecretKeyRing pgpSec = new PGPSecretKeyRing(testPrivKey, new BcKeyFingerprintCalculator());
PGPPublicKey pubKey = pgpPub.getPublicKey();
PGPUserAttributeSubpacketVectorGenerator vGen = new PGPUserAttributeSubpacketVectorGenerator();
vGen.setImageAttribute(ImageAttribute.JPEG, jpegImage);
PGPUserAttributeSubpacketVector uVec = vGen.generate();
PGPSignatureGenerator sGen = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA1));
sGen.init(PGPSignature.POSITIVE_CERTIFICATION, pgpSec.getSecretKey().extractPrivateKey(new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass)));
PGPSignature sig = sGen.generateCertification(uVec, pubKey);
PGPPublicKey nKey = PGPPublicKey.addCertification(pubKey, uVec, sig);
Iterator it = nKey.getUserAttributes();
int count = 0;
while (it.hasNext())
{
PGPUserAttributeSubpacketVector attributes = (PGPUserAttributeSubpacketVector)it.next();
Iterator sigs = nKey.getSignaturesForUserAttribute(attributes);
int sigCount = 0;
while (sigs.hasNext())
{
PGPSignature s = (PGPSignature)sigs.next();
s.init(new BcPGPContentVerifierBuilderProvider(), pubKey);
if (!s.verifyCertification(attributes, pubKey))
{
fail("added signature failed verification");
}
sigCount++;
}
if (sigCount != 1)
{
fail("Failed added user attributes signature check");
}
count++;
}
if (count != 1)
{
fail("didn't find added user attributes");
}
nKey = PGPPublicKey.removeCertification(nKey, uVec);
count = 0;
for (it = nKey.getUserAttributes(); it.hasNext();)
{
count++;
}
if (count != 0)
{
fail("found attributes where none expected");
}
}