本文整理匯總了Java中org.bouncycastle.openpgp.PGPException類的典型用法代碼示例。如果您正苦於以下問題:Java PGPException類的具體用法?Java PGPException怎麽用?Java PGPException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
PGPException類屬於org.bouncycastle.openpgp包,在下文中一共展示了PGPException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: readPublicKey
import org.bouncycastle.openpgp.PGPException; //導入依賴的package包/類
public static PGPPublicKey readPublicKey(InputStream in)
throws IOException, PGPException {
in = PGPUtil.getDecoderStream(in);
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in, new JcaKeyFingerprintCalculator() );
Iterator rIt = pgpPub.getKeyRings();
while (rIt.hasNext()) {
PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next();
Iterator kIt = kRing.getPublicKeys();
while (kIt.hasNext()) {
PGPPublicKey k = (PGPPublicKey) kIt.next();
if (k.isEncryptionKey()) {
return k;
}
}
}
throw new IllegalArgumentException(
"Can't find encryption key in key ring.");
}
示例2: getSecretKey
import org.bouncycastle.openpgp.PGPException; //導入依賴的package包/類
static PGPSecretKey getSecretKey(String privateKeyData) throws IOException, PGPException {
PGPPrivateKey privKey = null;
try (InputStream privStream = new ArmoredInputStream(new ByteArrayInputStream(privateKeyData.getBytes("UTF-8")))) {
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(privStream), new JcaKeyFingerprintCalculator());
Iterator keyRingIter = pgpSec.getKeyRings();
while (keyRingIter.hasNext()) {
PGPSecretKeyRing keyRing = (PGPSecretKeyRing)keyRingIter.next();
Iterator keyIter = keyRing.getSecretKeys();
while (keyIter.hasNext()) {
PGPSecretKey key = (PGPSecretKey)keyIter.next();
if (key.isSigningKey()) {
return key;
}
}
}
}
throw new IllegalArgumentException("Can't find signing key in key ring.");
}
示例3: signArmoredAscii
import org.bouncycastle.openpgp.PGPException; //導入依賴的package包/類
static String signArmoredAscii(PGPPrivateKey privateKey, String data, int signatureAlgo) throws IOException, PGPException {
String signature = null;
final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), signatureAlgo));
signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey);
ByteArrayOutputStream signatureOutput = new ByteArrayOutputStream();
try( BCPGOutputStream outputStream = new BCPGOutputStream( new ArmoredOutputStream(signatureOutput)) ) {
Utils.processStringAsStream(data, new StreamHandler() {
@Override
public void handleStreamBuffer(byte[] buffer, int offset, int length) throws IOException {
signatureGenerator.update(buffer, offset, length);
}
});
signatureGenerator.generate().encode(outputStream);
}
signature = new String(signatureOutput.toByteArray(), "UTF-8");
return signature;
}
示例4: getPublicKeyWithKeyIdAndUserID
import org.bouncycastle.openpgp.PGPException; //導入依賴的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: encrypt
import org.bouncycastle.openpgp.PGPException; //導入依賴的package包/類
/**
* Wraps with stream that outputs encrypted data packet.
*/
protected OutputStream encrypt(OutputStream out, FileMetadata meta)
throws IOException, PGPException {
if (log.isLoggable(Level.FINEST))
log.finest("using encryption algorithm " + encryptionAlgorithm);
if (encryptionAlgorithm == EncryptionAlgorithm.Unencrypted)
return null;
List<Key> keys = ring.getEncryptionKeys();
if (Util.isEmpty(keys) && Util.isEmpty(symmetricPassphrase))
throw new PGPException("no suitable encryption key found");
PGPEncryptedDataGenerator generator = buildEncryptor();
for (Key key : keys)
generator.addMethod(buildPublicKeyEncryptor(key));
if (!Util.isEmpty(symmetricPassphrase))
generator.addMethod(buildSymmetricKeyEncryptor());
return generator.open(out, getEncryptionBuffer(meta));
}
示例6: compress
import org.bouncycastle.openpgp.PGPException; //導入依賴的package包/類
/**
* Wraps with stream that outputs compressed data packet.
*/
protected OutputStream compress(OutputStream out, FileMetadata meta)
throws IOException, PGPException {
if (log.isLoggable(Level.FINEST))
log.finest("using compression algorithm " + compressionAlgorithm +
" -" + compressionLevel);
if (compressionAlgorithm == CompressionAlgorithm.Uncompressed ||
compressionLevel < 1 || compressionLevel > 9)
return null;
int algo = compressionAlgorithm.ordinal();
int level = compressionLevel;
byte[] buf = getCompressionBuffer(meta);
return new PGPCompressedDataGenerator(algo, level).open(out, buf);
}
示例7: decrypt
import org.bouncycastle.openpgp.PGPException; //導入依賴的package包/類
public static byte[] decrypt( byte encData[], PGPPrivateKey privateKey ) throws PGPException, IOException
{
PGPPublicKeyEncryptedData pgpEncData = getPGPEncryptedData( encData );
InputStream is = getInputStream( privateKey, pgpEncData );
// IMPORTANT: pipe() should be before verify(). Otherwise we get "java.io.EOFException: Unexpected end of ZIP
// input stream".
byte data[] = pipe( is );
if ( !pgpEncData.verify() )
{
throw new PGPDataValidationException( "Data integrity check failed" );
}
return data;
}
示例8: openDecryptor
import org.bouncycastle.openpgp.PGPException; //導入依賴的package包/類
/**
* Opens a new {@link Decryptor} (Reading Step 1/3)
*
* <p>This is the first step in opening a ghostryde file. After this method, you'll want to
* call {@link #openDecompressor(Decryptor)}.
*
* @param input is an {@link InputStream} of the ghostryde file data.
* @param privateKey is the private encryption key of the recipient (which is us!)
* @throws IOException
* @throws PGPException
*/
@CheckReturnValue
public Decryptor openDecryptor(@WillNotClose InputStream input, PGPPrivateKey privateKey)
throws IOException, PGPException {
checkNotNull(privateKey, "privateKey");
PGPObjectFactory fact = new BcPGPObjectFactory(checkNotNull(input, "input"));
PGPEncryptedDataList crypts = pgpCast(fact.nextObject(), PGPEncryptedDataList.class);
checkState(crypts.size() > 0);
if (crypts.size() > 1) {
logger.warningfmt("crypts.size() is %d (should be 1)", crypts.size());
}
PGPPublicKeyEncryptedData crypt = pgpCast(crypts.get(0), PGPPublicKeyEncryptedData.class);
if (crypt.getKeyID() != privateKey.getKeyID()) {
throw new PGPException(String.format(
"Message was encrypted for keyid %x but ours is %x",
crypt.getKeyID(), privateKey.getKeyID()));
}
return new Decryptor(
crypt.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey)),
crypt);
}
示例9: signExternal
import org.bouncycastle.openpgp.PGPException; //導入依賴的package包/類
public byte[] signExternal(String input) throws IOException, PGPException {
PGPSecretKey signKey = readSecretKey();
PGPPrivateKey privKey = signKey.extractPrivateKey(
new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray()));
PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator(
new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC"));
sigGenerator.init(PGPSignature.BINARY_DOCUMENT, privKey);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) {
BCPGOutputStream bOut = new BCPGOutputStream(aOut);
sigGenerator.update(input.getBytes(Charsets.UTF_8));
sigGenerator.generate().encode(bOut);
}
return buffer.toByteArray();
}
示例10: getRelationChallenge
import org.bouncycastle.openpgp.PGPException; //導入依賴的package包/類
@Override
public String getRelationChallenge( final long ttl ) throws RelationVerificationException
{
RelationChallengeImpl relationToken = new RelationChallengeImpl( ttl );
relationDataService.save( relationToken );
String content = JsonUtil.toJson( relationToken );
securityManager.getKeyManager().getPublicKey( null );
try
{
KeyManager keyManager = securityManager.getKeyManager();
byte[] encBytes = PGPEncryptionUtil.encrypt( content.getBytes(), keyManager.getPublicKey( null ), true );
return "\n" + new String( encBytes, "UTF-8" );
}
catch ( UnsupportedEncodingException | PGPException e )
{
logger.error( "Error encrypting message for relation challenge", e );
throw new RelationVerificationException( "Error encrypting message for relation challenge", e );
}
}
示例11: addPeerEnvironmentPubKey
import org.bouncycastle.openpgp.PGPException; //導入依賴的package包/類
@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() );
}
}
示例12: lookupPublicKey
import org.bouncycastle.openpgp.PGPException; //導入依賴的package包/類
/**
* Search for public key on keyring based on a substring (like an email address).
*
* @throws VerifyException if the key couldn't be found.
* @see #lookupKeyPair
*/
public static PGPPublicKey lookupPublicKey(
PGPPublicKeyRingCollection keyring, String query, KeyRequirement want) {
try {
// Safe by specification.
@SuppressWarnings("unchecked")
Iterator<PGPPublicKeyRing> results =
keyring.getKeyRings(checkNotNull(query, "query"), true, true);
verify(results.hasNext(), "No public key found matching substring: %s", query);
while (results.hasNext()) {
Optional<PGPPublicKey> result = lookupPublicSubkey(results.next(), want);
if (result.isPresent()) {
return result.get();
}
}
throw new VerifyException(String.format(
"No public key (%s) found matching substring: %s", want, query));
} catch (PGPException e) {
throw new VerifyException(String.format(
"Public key lookup with query %s failed: %s", query, e.getMessage()));
}
}
示例13: determineSecretKeysWithPrivateKeyAndUserId
import org.bouncycastle.openpgp.PGPException; //導入依賴的package包/類
public List<PGPSecretKeyAndPrivateKeyAndUserId> determineSecretKeysWithPrivateKeyAndUserId(Exchange exchange, String sigKeyFileName,
List<String> sigKeyUserids, String sigKeyPassword, byte[] sigKeyRing) throws IOException, PGPException, NoSuchProviderException {
Map<String, String> sigKeyUserId2Password = determineSignatureKeyUserId2Password(sigKeyUserids, sigKeyPassword);
List<PGPSecretKeyAndPrivateKeyAndUserId> sigSecretKeysWithPrivateKeyAndUserId = PGPDataFormatUtil
.findSecretKeysWithPrivateKeyAndUserId(exchange.getContext(), sigKeyFileName, sigKeyRing, sigKeyUserId2Password,
getProvider());
if (sigSecretKeysWithPrivateKeyAndUserId.isEmpty()) {
throw new IllegalArgumentException(
String.format(
"Cannot PGP sign message. No secret key found for User IDs %s. Either add keys with this User IDs to the secret keyring or change the configured User IDs.",
sigKeyUserids));
}
return sigSecretKeysWithPrivateKeyAndUserId;
}
示例14: setSig
import org.bouncycastle.openpgp.PGPException; //導入依賴的package包/類
public void setSig(PGPSignature s) throws PGPException {
sig = s;
if (sig1 != null) return;
key = getRing().findById(s.getKeyID());
if (key == null) {
if (Decryptor.this.log.isLoggable(Level.INFO))
Decryptor.this.log.info("not found verification key " +
Util.formatKeyId(s.getKeyID()));
return;
}
Subkey subkey = key.findById(s.getKeyID());
if (subkey == null || !subkey.isForVerification())
key = null;
else
s.init(getVerifierProvider(), subkey.getPublicKey());
if (Decryptor.this.log.isLoggable(Level.INFO))
Decryptor.this.log.info((key == null ? "not " : "") +
"using verification key " + subkey);
}
示例15: createEncryptedNonCompressedData
import org.bouncycastle.openpgp.PGPException; //導入依賴的package包/類
void createEncryptedNonCompressedData(ByteArrayOutputStream bos, String keyringPath) throws Exception, IOException, PGPException,
UnsupportedEncodingException {
PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5)
.setSecureRandom(new SecureRandom()).setProvider(getProvider()));
encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(readPublicKey(keyringPath)));
OutputStream encOut = encGen.open(bos, new byte[512]);
PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator();
OutputStream litOut = litData.open(encOut, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, new Date(), new byte[512]);
try {
litOut.write("Test Message Without Compression".getBytes("UTF-8"));
litOut.flush();
} finally {
IOHelper.close(litOut);
IOHelper.close(encOut, bos);
}
}