Java源码示例:org.bouncycastle.openpgp.PGPPublicKeyRing
示例1
private PGPPublicKeyRing importKey(PGPPublicKeyRing keyring) throws IOException, PGPException {
String fpr = PGPUtils.getFingerprint(keyring);
PGPPublicKeyRing newring;
PGPPublicKeyRing oldring = getKey(fpr);
if (oldring != null) {
newring = PGPUtils.merge(oldring, keyring);
}
else {
newring = keyring;
}
try {
db.put(null, new DatabaseEntry(fingerprintKey(fpr)), new DatabaseEntry(newring.getEncoded()));
}
catch (DatabaseException e) {
throw new IOException("Database error", e);
}
return newring;
}
示例2
private boolean verifySignatureStatus(boolean signatureStatus, Artifact artifact,
PGPPublicKey publicKey, PGPPublicKeyRing publicKeyRing) {
if (signatureStatus) {
logWithQuiet.accept(() -> String.format(PGP_VERIFICATION_RESULT_FORMAT, artifact.getId(),
"OK", PublicKeyUtils.keyIdDescription(publicKey, publicKeyRing),
PublicKeyUtils.getUserIDs(publicKey, publicKeyRing)));
return true;
} else if (keysMap.isBrokenSignature(artifact)) {
logWithQuiet.accept(() ->
String.format("%s PGP Signature is broken, consistent with keys map.", artifact.getId()));
return true;
}
getLog().error(String.format(PGP_VERIFICATION_RESULT_FORMAT, artifact.getId(),
"INVALID", PublicKeyUtils.keyIdDescription(publicKey, publicKeyRing),
PublicKeyUtils.getUserIDs(publicKey, publicKeyRing)));
return false;
}
示例3
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject();
try {
if (ois.readBoolean()) {
secretKeyRing = new PGPSecretKeyRing(initInputStream(ois),
KeyFilesOperationsPgpImpl.fingerprintCalculator);
}
if (ois.readBoolean()) {
publicKeyRing = new PGPPublicKeyRing(initInputStream(ois),
KeyFilesOperationsPgpImpl.fingerprintCalculator);
}
} catch (PGPException e) {
throw new IOException("Failed to read key", e);
}
}
示例4
public PGPPublicKeyRing getKeyRing(PGPKeyId keyID) throws IOException, PGPException {
Optional<PGPPublicKeyRing> keyRing = Optional.empty();
String path = keyID.getHashPath();
File keyFile = new File(cachePath, path);
synchronized (LOCK) {
if (!keyFile.exists()) {
keyServerList.execute(keysServerClient -> receiveKey(keyFile, keyID, keysServerClient));
}
try (InputStream keyFileStream = new FileInputStream(keyFile)) {
keyRing = PublicKeyUtils.loadPublicKeyRing(keyFileStream, keyID);
return keyRing.orElseThrow(() ->
new PGPException(String.format("Can't find public key %s in download file: %s",
keyID, keyFile)));
} finally {
if (!keyRing.isPresent()) {
deleteFile(keyFile);
}
}
}
}
示例5
/**
* Loads all keys from the specified input stream,
* and adds them to this ring's existing list of keys.
*/
public List<Key> load(InputStream stream) throws IOException, PGPException {
List<Key> keys = new ArrayList<Key>();
Iterator<?> packets = parse(stream);
while (packets.hasNext()) {
Object packet = packets.next();
if (packet instanceof PGPSecretKeyRing)
keys.add(newKey((PGPSecretKeyRing) packet));
else if (packet instanceof PGPPublicKeyRing)
keys.add(newKey((PGPPublicKeyRing) packet));
else if (packet instanceof PublicKeyRingBlob)
keys.add(newKey(
((PublicKeyRingBlob) packet).getPGPPublicKeyRing()));
}
this.keys.addAll(keys);
return keys;
}
示例6
public static PGPPublicKey readPublicKey( InputStream is ) throws IOException, PGPException
{
PGPPublicKeyRingCollection pgpPub =
new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( is ), new JcaKeyFingerprintCalculator() );
Iterator keyRingIter = pgpPub.getKeyRings();
while ( keyRingIter.hasNext() )
{
PGPPublicKeyRing keyRing = ( PGPPublicKeyRing ) keyRingIter.next();
Iterator keyIter = keyRing.getPublicKeys();
while ( keyIter.hasNext() )
{
PGPPublicKey key = ( PGPPublicKey ) keyIter.next();
if ( key.isEncryptionKey() )
{
return key;
}
}
}
throw new IllegalArgumentException( "Can't find encryption key in key ring." );
}
示例7
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 );
}
}
示例8
@Test
public void testSubKeyMach() throws IOException, PGPException {
try (InputStream inputStream = getClass().getResourceAsStream("/EFE8086F9E93774E.asc")) {
Optional<PGPPublicKeyRing> aPublicKeyRing = PublicKeyUtils.loadPublicKeyRing(inputStream, PGPKeyId.from(0xEFE8086F9E93774EL));
assertThat(aPublicKeyRing)
.hasValueSatisfying(publicKeyRing -> {
// keyInfo with master key fingerprint
KeyInfo keyInfo = new KeyInfo(PublicKeyUtils.fingerprint(publicKeyRing.getPublicKey()));
assertThat(keyInfo.isKeyMatch(publicKeyRing.getPublicKey(0xEFE8086F9E93774EL), publicKeyRing))
.isTrue();
});
}
}
示例9
@Override
public Peer call() throws Exception
{
RelationLinkDto relationLinkDto = new RelationLinkDto( environment );
PublicKeyContainer publicKeyContainer = peer.createPeerEnvironmentKeyPair( relationLinkDto );
PGPPublicKeyRing pubRing = getPublicKey( publicKeyContainer );
PGPPublicKeyRing signedPEK = keyManager.setKeyTrust( envSecKeyRing, pubRing, KeyTrustLevel.FULL.getId() );
peer.updatePeerEnvironmentPubKey( environment.getEnvironmentId(), signedPEK );
peer.addPeerEnvironmentPubKey( localPeer.getId() + "_" + environment.getEnvironmentId().getId(),
localPeerSignedPEK );
localPeer.addPeerEnvironmentPubKey( peer.getId() + "_" + environment.getEnvironmentId().getId(), signedPEK );
return peer;
}
示例10
@Override
public void addPeerEnvironmentPubKey( final String keyId, final PGPPublicKeyRing pek ) throws PeerException
{
Preconditions.checkNotNull( keyId, "Invalid key ID" );
Preconditions.checkNotNull( pek, "Public key ring is null" );
try
{
String exportedPubKeyRing = securityManager.getEncryptionTool().armorByteArrayToString( pek.getEncoded() );
peerWebClient.addPeerEnvironmentPubKey( keyId, exportedPubKeyRing );
}
catch ( IOException | PGPException e )
{
throw new PeerException( e.getMessage() );
}
}
示例11
/**
* Return a {@link Set} of {@link OpenPgpV4Fingerprint}s of all keys in {@code publicKeys}, which are marked with the
* {@link OpenPgpTrustStore.Trust} of {@code trust}.
*
* @param publicKeys {@link PGPPublicKeyRingCollection} of keys which are iterated.
* @param trust {@link OpenPgpTrustStore.Trust} state.
* @return {@link Set} of fingerprints
*
* @throws IOException IO error
*/
public Set<OpenPgpV4Fingerprint> getFingerprintsOfKeysWithState(PGPPublicKeyRingCollection publicKeys,
OpenPgpTrustStore.Trust trust)
throws IOException {
PGPPublicKeyRingCollection keys = getPublicKeysOfTrustState(publicKeys, trust);
Set<OpenPgpV4Fingerprint> fingerprints = new HashSet<>();
if (keys == null) {
return fingerprints;
}
for (PGPPublicKeyRing ring : keys) {
fingerprints.add(new OpenPgpV4Fingerprint(ring));
}
return fingerprints;
}
示例12
@Override
public PGPPublicKeyRing signKey( PGPSecretKeyRing sourceSecRing, PGPPublicKeyRing targetPubRing, int trustLevel )
{
try
{
String sigId = PGPKeyUtil.encodeNumericKeyId( targetPubRing.getPublicKey().getKeyID() );
targetPubRing = encryptionTool.signPublicKey( targetPubRing, sigId, sourceSecRing.getSecretKey(), "" );
}
catch ( Exception ignored )
{
//ignore
}
return targetPubRing;
}
示例13
@Override
public String signPublicKey( String sourceIdentityId, String keyText, int trustLevel )
{
String keyStr = "";
try
{
PGPPublicKeyRing targetPubRing = PGPKeyUtil.readPublicKeyRing( keyText );
PGPSecretKeyRing sourceSecRing = getSecretKeyRing( sourceIdentityId );
targetPubRing = signKey( sourceSecRing, targetPubRing, trustLevel );
keyStr = encryptionTool.armorByteArrayToString( targetPubRing.getEncoded() );
}
catch ( Exception ex )
{
LOG.error( "**** Error !!! Error signing key, IdentityId: " + sourceIdentityId, ex );
}
return keyStr;
}
示例14
@Test
public void getKeyFromCache() throws IOException, PGPException {
PGPKeysCache pgpKeysCache = new PGPKeysCache(cachePath.toFile(), keysServerClients, true);
// first call retrieve key from server
PGPPublicKeyRing keyRing = pgpKeysCache.getKeyRing(PGPKeyId.from(0xEFE8086F9E93774EL));
assertThat(keyRing)
.hasSize(2)
.anyMatch(key -> key.getKeyID() == 0xEFE8086F9E93774EL);
verify(keysServerClients.get(0)).getUriForGetKey(any(PGPKeyId.class));
verify(keysServerClients.get(0)).copyKeyToOutputStream(any(PGPKeyIdLong.class), any(OutputStream.class), any(PGPKeysServerClient.OnRetryConsumer.class));
verifyNoMoreInteractions(keysServerClients.get(0));
clearInvocations(keysServerClients.get(0));
// second from cache
keyRing = pgpKeysCache.getKeyRing(PGPKeyId.from(0xEFE8086F9E93774EL));
assertThat(keyRing)
.hasSize(2)
.anyMatch(key -> key.getKeyID() == 0xEFE8086F9E93774EL);
verifyNoInteractions(keysServerClients.get(0));
}
示例15
@Override
public PGPPublicKeyRing getPublicKeyRingByFingerprint( String fingerprint )
{
try
{
byte[] aKeyData = keyServer.getPublicKeyByFingerprint( fingerprint ).getKeyData();
if ( aKeyData != null )
{
return PGPKeyUtil.readPublicKeyRing( aKeyData );
}
}
catch ( Exception e )
{
return null;
}
return null;
}
示例16
@Override
public PGPPublicKey getRemoteHostPublicKey( final String hostIdTarget )
{
try
{
PGPPublicKeyRing pubRing;
pubRing = getPublicKeyRing( hostIdTarget );
if ( pubRing != null )
{
return PGPKeyUtil.readPublicKey( pubRing );
}
}
catch ( Exception ex )
{
// ignore
}
return null;
}
示例17
/**
* 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
*/
@Override
public PGPPublicKeyRing signPublicKey( PGPPublicKeyRing publicKeyRing, String id, PGPSecretKey secretKey,
String secretKeyPassword )
{
try
{
if ( StringUtils.isBlank( secretKeyPassword ) )
{
secretKeyPassword = keyManager.getSecurityKeyData().getSecretKeyringPwd();
}
return PGPEncryptionUtil.signPublicKey( publicKeyRing, id, secretKey, secretKeyPassword );
}
catch ( Exception e )
{
//throw custom exception
throw new ActionFailedException( e );
}
}
示例18
PGPSecretKeyRing createEnvironmentKeyPair( EnvironmentId envId ) throws EnvironmentCreationException
{
KeyManager keyManager = securityManager.getKeyManager();
String pairId = envId.getId();
try
{
KeyPair keyPair = keyManager.generateKeyPair( pairId, false );
//******Create PEK *****************************************************************
PGPSecretKeyRing secRing = pgpKeyUtil.getSecretKeyRing( keyPair.getSecKeyring() );
PGPPublicKeyRing pubRing = pgpKeyUtil.getPublicKeyRing( keyPair.getPubKeyring() );
//***************Save Keys *********************************************************
keyManager.saveSecretKeyRing( pairId, SecurityKeyType.ENVIRONMENT_KEY.getId(), secRing );
keyManager.savePublicKeyRing( pairId, SecurityKeyType.ENVIRONMENT_KEY.getId(), pubRing );
return secRing;
}
catch ( PGPException ex )
{
throw new EnvironmentCreationException( ex );
}
}
示例19
@SuppressWarnings("rawtypes")
public static PGPPublicKey getPublicKey(String userId, String publicKeyringFile) throws IOException, PGPException {
// TODO: Reevaluate the mechanism for executing this task as performance can suffer here and only a specific key needs to be validated
// Read in from the public keyring file
try (FileInputStream keyInputStream = new FileInputStream(publicKeyringFile)) {
// Form the PublicKeyRing collection (1.53 way with fingerprint calculator)
PGPPublicKeyRingCollection pgpPublicKeyRingCollection = new PGPPublicKeyRingCollection(keyInputStream, new BcKeyFingerprintCalculator());
// Iterate over all public keyrings
Iterator<PGPPublicKeyRing> iter = pgpPublicKeyRingCollection.getKeyRings();
PGPPublicKeyRing keyRing;
while (iter.hasNext()) {
keyRing = iter.next();
// Iterate over each public key in this keyring
Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys();
while (keyIter.hasNext()) {
PGPPublicKey publicKey = keyIter.next();
// Iterate over each userId attached to the public key
Iterator userIdIterator = publicKey.getUserIDs();
while (userIdIterator.hasNext()) {
String id = (String) userIdIterator.next();
if (userId.equalsIgnoreCase(id)) {
return publicKey;
}
}
}
}
}
// If this point is reached, no public key could be extracted with the given userId
throw new PGPException("Could not find a public key with the given userId");
}
示例20
public PeerEnvironmentKeyTask( final LocalPeer localPeer, final PGPSecretKeyRing envSecKeyRing,
final PGPPublicKeyRing localPeerSignedPEK, final Environment environment,
final Peer peer, final KeyManager keyManager )
{
this.localPeer = localPeer;
this.envSecKeyRing = envSecKeyRing;
this.localPeerSignedPEK = localPeerSignedPEK;
this.environment = environment;
this.peer = peer;
this.keyManager = keyManager;
}
示例21
public static KeyPair generateKeyPair( String userId, String secretPwd, boolean armored ) throws PGPException
{
try
{
KeyPair keyPair = new KeyPair();
PGPKeyRingGenerator krgen = generateKeyRingGenerator( userId, secretPwd, keyPair );
// Generate public key ring
PGPPublicKeyRing pkr = krgen.generatePublicKeyRing();
ByteArrayOutputStream pubOut = new ByteArrayOutputStream();
pkr.encode( pubOut );
pubOut.close();
// Generate private key
PGPSecretKeyRing skr = krgen.generateSecretKeyRing();
ByteArrayOutputStream secOut = new ByteArrayOutputStream();
skr.encode( secOut );
secOut.close();
keyPair.setPubKeyring( armored ? armorByteArray( pubOut.toByteArray() ) : pubOut.toByteArray() );
keyPair.setSecKeyring( armored ? armorByteArray( secOut.toByteArray() ) : secOut.toByteArray() );
return keyPair;
}
catch ( Exception e )
{
throw new PGPException( "Error in generateKeyPair", e );
}
}
示例22
/**
* 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 );
}
}
示例23
public static Collection<String> getUserIDs(PGPPublicKey publicKey, PGPPublicKeyRing publicKeyRing) {
// use getRawUserIDs and standard java String to transform byte array to utf8
// because BC generate exception if there is some problem in decoding utf8
// https://github.com/s4u/pgpverify-maven-plugin/issues/61
Set<byte[]> ret = new LinkedHashSet<>();
publicKey.getRawUserIDs().forEachRemaining(ret::add);
getMasterKey(publicKey, publicKeyRing).ifPresent(masterKey ->
masterKey.getRawUserIDs().forEachRemaining(ret::add)
);
return ret.stream()
.map(b -> new String(b, StandardCharsets.UTF_8))
.collect(Collectors.toSet());
}
示例24
private PGPPublicKeyRing getKey(byte[] fingerprint) throws IOException, PGPException {
byte[] data = db.get(fingerprint);
if (data != null)
return PGPUtils.readPublicKeyring(data);
return null;
}
示例25
/** Validates the given key for expiration, revocation and signature by the server. */
private BareJID validate(PGPPublicKeyRing key) throws PGPException {
PGPPublicKey masterKey = PGPUtils.getMasterKey(key);
if (masterKey == null || PGPUtils.isRevoked(masterKey) || PGPUtils.isExpired(masterKey))
return null;
PGPUserID uid = PGPUtils.findUserID(masterKey, domain);
if (uid != null) {
if (PGPUtils.findValidKeySignature(masterKey, uid.toString(), secretMasterKey)) {
return BareJID.bareJIDInstanceNS(uid.getEmail());
}
}
return null;
}
示例26
@Test
public void testVerifyKey() throws Exception
{
PGPPublicKeyRing pgpPublicKey = PGPKeyUtil.readPublicKeyRing( findFile( PUBLIC_KEYRING ) );
PGPSecretKey pgpSecretKey = PGPEncryptionUtil.findSecretKeyById( findFile( SECRET_KEYRING ), SECRET_KEY_ID );
PGPPublicKeyRing signedPubKey =
PGPEncryptionUtil.signPublicKey( pgpPublicKey, USER_ID, pgpSecretKey, SECRET_PWD );
assertTrue( PGPEncryptionUtil
.verifyPublicKey( signedPubKey.getPublicKey(), USER_ID, pgpSecretKey.getPublicKey() ) );
}
示例27
@Test
public void testKeySigning() throws PGPException, IOException
{
KeyPair first = PGPEncryptionUtil.generateKeyPair( "[email protected]", "first", false );
KeyPair second = PGPEncryptionUtil.generateKeyPair( "[email protected]", "second", false );
signKeyAndPrintIds( first, second, "second" );
InputStream firstPublicStream = new ByteArrayInputStream( first.getPubKeyring() );
InputStream secondPublicStream = new ByteArrayInputStream( second.getPubKeyring() );
PGPPublicKeyRingCollection firstPublicKeyRingCollection =
new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( firstPublicStream ),
new JcaKeyFingerprintCalculator() );
PGPPublicKeyRingCollection secondPublicKeyRingCollection =
new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( secondPublicStream ),
new JcaKeyFingerprintCalculator() );
if ( firstPublicKeyRingCollection.getKeyRings().hasNext() )
{
PGPPublicKeyRing firstPublicKeyRing = null;
PGPPublicKeyRing secondPublicKeyRing = null;
firstPublicKeyRing = firstPublicKeyRingCollection.getKeyRings().next();
secondPublicKeyRing = secondPublicKeyRingCollection.getKeyRings().next();
assertEquals( true,
printPublicKeySignatures( firstPublicKeyRing.getPublicKey(), secondPublicKeyRing.getPublicKey() ) );
}
}
示例28
private void signKeyAndPrintIds( KeyPair first, KeyPair second, String password ) throws IOException, PGPException
{
InputStream firstPublicStream = new ByteArrayInputStream( first.getPubKeyring() );
InputStream secondPublicStream = new ByteArrayInputStream( second.getPubKeyring() );
InputStream secondSecretStream = new ByteArrayInputStream( second.getSecKeyring() );
PGPPublicKeyRingCollection keyrings =
new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( firstPublicStream ),
new JcaKeyFingerprintCalculator() );
PGPPublicKeyRing firstPublicKeyRing = null;
if ( keyrings.getKeyRings().hasNext() )
{
firstPublicKeyRing = keyrings.getKeyRings().next();
PGPSecretKey secondSecretKey =
PGPEncryptionUtil.findSecretKeyById( secondSecretStream, second.getPrimaryKeyId() );
PGPPublicKey secondPublicKey =
PGPEncryptionUtil.findPublicKeyById( secondPublicStream, second.getPrimaryKeyId() );
if ( secondSecretKey != null )
{
String keyId = Long.toHexString( secondSecretKey.getKeyID() );
PGPPublicKeyRing firstSignedPublicKeyRing =
PGPEncryptionUtil.signPublicKey( firstPublicKeyRing, keyId, secondSecretKey, password );
printPublicKeySignatures( firstSignedPublicKeyRing.getPublicKey(), secondPublicKey );
first.setPubKeyring( firstSignedPublicKeyRing.getEncoded() );
}
}
}
示例29
private PGPPublicKeyRing importKey(PGPPublicKeyRing keyring) throws IOException, PGPException {
String fpr = PGPUtils.getFingerprint(keyring);
PGPPublicKeyRing newring;
PGPPublicKeyRing oldring = getKey(fpr);
if (oldring != null) {
newring = PGPUtils.merge(oldring, keyring);
}
else {
newring = keyring;
}
db.set(fingerprintKey(fpr), newring.getEncoded());
return newring;
}
示例30
@Test
public void testVerifyClearSign() throws Exception
{
InputStream secondPublicStream = findFile( PLUGIN_PUBLIC_KEY );
PGPPublicKeyRingCollection secondPublicKeyRingCollection =
new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( secondPublicStream ),
new JcaKeyFingerprintCalculator() );
PGPPublicKeyRing pgpKeyring = secondPublicKeyRingCollection
.getPublicKeyRing( secondPublicKeyRingCollection.iterator().next().getPublicKey().getKeyID() );
String signedMessage = IOUtils.toString( findFile( "signedMessage.txt" ) );
logger.info( "\n" + signedMessage );
boolean result = PGPEncryptionUtil.verifyClearSign( signedMessage.getBytes(), pgpKeyring );
if ( result )
{
logger.info( "signature verified." );
}
else
{
logger.info( "signature verification failed." );
}
assertEquals( true, result );
}