Java 类org.bouncycastle.openpgp.PGPPrivateKey 实例源码

项目:base    文件:PGPEncryptionUtil.java   
private static PGPLiteralData asLiteral( final byte[] message, final InputStream secretKeyRing,
                                         final String secretPwd ) throws IOException, PGPException
{
    PGPPrivateKey key = null;
    PGPPublicKeyEncryptedData encrypted = null;
    final PGPSecretKeyRingCollection keys =
            new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream( secretKeyRing ),
                    new JcaKeyFingerprintCalculator() );
    for ( final Iterator<PGPPublicKeyEncryptedData> i = getEncryptedObjects( message );
          ( key == null ) && i.hasNext(); )
    {
        encrypted = i.next();
        key = getPrivateKey( keys, encrypted.getKeyID(), secretPwd );
    }
    if ( key == null )
    {
        throw new IllegalArgumentException( "secret key for message not found." );
    }
    final InputStream stream = encrypted
            .getDataStream( new JcePublicKeyDataDecryptorFactoryBuilder().setProvider( provider ).build( key ) );
    return asLiteral( stream );
}
项目:react-native-pgp    文件:Module.java   
@ReactMethod
public void signData(final String privKeyData, final String password, final String data, Promise promise) {
  try {
    // region Decode Private Key
    PGPSecretKey secKey = PGPUtils.getSecretKey(privKeyData);
    PGPPrivateKey privKey = PGPUtils.decryptArmoredPrivateKey(secKey, password);
    // endregion
    // region Sign Data
    String signature = PGPUtils.signArmoredAscii(privKey, data, signatureAlgo);
    WritableMap resultMap = Arguments.createMap();
    resultMap.putString("asciiArmoredSignature", signature);
    resultMap.putString("hashingAlgo",  PGPUtils.hashAlgoToString(signatureAlgo));
    resultMap.putString("fingerPrint", Utils.bytesToHex(secKey.getPublicKey().getFingerprint()));
    promise.resolve(resultMap);
    // endregion
  } catch (Exception e) {
    promise.reject(e);
  }
}
项目:react-native-pgp    文件:Module.java   
@ReactMethod
public void signB64Data(final String privKeyData, final String password, final String b64Data, Promise promise) {
  try {
    // region Decode Base64
    byte[] data = Base64.decode(b64Data, Base64.DEFAULT);
    // endregion
    // region Decode Private Key
    PGPSecretKey secKey = PGPUtils.getSecretKey(privKeyData);
    PGPPrivateKey privKey = PGPUtils.decryptArmoredPrivateKey(secKey, password);
    // endregion
    // region Sign Data
    String signature = PGPUtils.signArmoredAscii(privKey, data, signatureAlgo);
    WritableMap resultMap = Arguments.createMap();
    resultMap.putString("asciiArmoredSignature", signature);
    resultMap.putString("hashingAlgo",  PGPUtils.hashAlgoToString(signatureAlgo));
    resultMap.putString("fingerPrint", Utils.bytesToHex(secKey.getPublicKey().getFingerprint()));
    promise.resolve(resultMap);
    // endregion
  } catch (Exception e) {
    promise.reject(e);
  }
}
项目:react-native-pgp    文件:PGPUtils.java   
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.");
}
项目:react-native-pgp    文件:PGPUtils.java   
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;
}
项目:react-native-pgp    文件:PGPUtils.java   
static String signArmoredAscii(PGPPrivateKey privateKey, byte[] 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.processByteArrayAsStream(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;
}
项目:base    文件:PGPEncryptionUtil.java   
/**
 * ***********************************************
 */
private static PGPPrivateKey getPrivateKey( final PGPSecretKeyRingCollection keys, final long id,
                                            final String secretPwd )
{
    try
    {
        final PGPSecretKey key = keys.getSecretKey( id );
        if ( key != null )
        {
            return key.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider )
                                                                               .build( secretPwd.toCharArray() ) );
        }
    }
    catch ( final Exception e )
    {
        // Don't print the passphrase but do print null if thats what it was
        final String passphraseMessage = ( secretPwd == null ) ? "null" : "supplied";
        LOG.warn( "Unable to extract key " + id + " using " + passphraseMessage + " passphrase: {}",
                e.getMessage() );
    }
    return null;
}
项目:base    文件:PGPEncryptionUtil.java   
/**
 * ***********************************************
 */
public static PGPPrivateKey getPrivateKey( final PGPSecretKey secretKey, final String secretPwd )
{
    Preconditions.checkNotNull( secretKey );
    Preconditions.checkNotNull( secretPwd );

    try
    {
        return secretKey.extractPrivateKey(
                new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) );
    }
    catch ( Exception e )
    {
        LOG.error( "Unable to extract key {}: {}", secretKey.getKeyID(), e.getMessage() );
    }

    return null;
}
项目:base    文件:PGPDecrypt.java   
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;
}
项目:base    文件:PGPEncryptDecryptTest.java   
private static void test( byte data[], PGPPrivateKey privateKey, PGPPublicKey publicKey ) throws Exception
{
    byte encData[] = PGPEncrypt.encrypt( data, publicKey );

    byte decData[] = PGPDecrypt.decrypt( encData, privateKey );

    assertArrayEquals( data, decData );
}
项目:nomulus    文件:Ghostryde.java   
/**
 * Deciphers a ghostryde file from an in-memory byte array.
 *
 * @throws PGPException
 * @throws IOException
 */
public static DecodeResult decode(byte[] data, PGPPrivateKey key)
    throws IOException, PGPException {
  checkNotNull(data, "data");
  Ghostryde ghost = new Ghostryde(1024 * 64);
  ByteArrayInputStream dataStream = new ByteArrayInputStream(data);
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  String name;
  DateTime modified;
  try (Decryptor decryptor = ghost.openDecryptor(dataStream, key);
      Decompressor decompressor = ghost.openDecompressor(decryptor);
      Input input = ghost.openInput(decompressor)) {
    name = input.getName();
    modified = input.getModified();
    ByteStreams.copy(input, output);
  }
  return new DecodeResult(output.toByteArray(), name, modified);
}
项目:nomulus    文件:Ghostryde.java   
/**
 * 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);
}
项目:nomulus    文件:PgpHelper.java   
/**
 * Same as {@link #lookupPublicKey} but also retrieves the associated private key.
 *
 * @throws VerifyException if either keys couldn't be found.
 * @see #lookupPublicKey
 */
@SuppressWarnings("deprecation")
public static PGPKeyPair lookupKeyPair(
    PGPPublicKeyRingCollection publics,
    PGPSecretKeyRingCollection privates,
    String query,
    KeyRequirement want) {
  PGPPublicKey publicKey = lookupPublicKey(publics, query, want);
  PGPPrivateKey privateKey;
  try {
    PGPSecretKey secret = verifyNotNull(privates.getSecretKey(publicKey.getKeyID()),
        "Keyring missing private key associated with public key id: %x (query '%s')",
        publicKey.getKeyID(), query);
    // We do not support putting a password on the private key so we're just going to
    // put char[0] here.
    privateKey = secret.extractPrivateKey(
        new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
            .build(new char[0]));
  } catch (PGPException e) {
    throw new VerifyException(e.getMessage());
  }
  return new PGPKeyPair(publicKey, privateKey);
}
项目:nomulus    文件:GhostrydeTest.java   
@Theory
public void testEncryptOnly(Content content) throws Exception {
  Keyring keyring = new FakeKeyringModule().get();
  byte[] data = content.get().getBytes(UTF_8);
  PGPPublicKey publicKey = keyring.getRdeStagingEncryptionKey();
  PGPPrivateKey privateKey = keyring.getRdeStagingDecryptionKey();

  Ghostryde ghost = new Ghostryde(1024);
  ByteArrayOutputStream bsOut = new ByteArrayOutputStream();
  try (Ghostryde.Encryptor encryptor = ghost.openEncryptor(bsOut, publicKey)) {
    encryptor.write(data);
  }

  ByteArrayInputStream bsIn = new ByteArrayInputStream(bsOut.toByteArray());
  bsOut.reset();
  try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey)) {
    ByteStreams.copy(decryptor, bsOut);
  }

  assertThat(new String(bsOut.toByteArray(), UTF_8)).isEqualTo(content.get());
}
项目:nomulus    文件:GhostrydeTest.java   
@Theory
public void testEncryptCompressOnly(Content content) throws Exception {
  Keyring keyring = new FakeKeyringModule().get();
  PGPPublicKey publicKey = keyring.getRdeStagingEncryptionKey();
  PGPPrivateKey privateKey = keyring.getRdeStagingDecryptionKey();
  byte[] data = content.get().getBytes(UTF_8);

  Ghostryde ghost = new Ghostryde(1024);
  ByteArrayOutputStream bsOut = new ByteArrayOutputStream();
  try (Ghostryde.Encryptor encryptor = ghost.openEncryptor(bsOut, publicKey);
      Ghostryde.Compressor kompressor = ghost.openCompressor(encryptor)) {
    kompressor.write(data);
  }

  assertThat(new String(bsOut.toByteArray(), UTF_8)).isNotEqualTo(content.get());

  ByteArrayInputStream bsIn = new ByteArrayInputStream(bsOut.toByteArray());
  bsOut.reset();
  try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey);
      Ghostryde.Decompressor decompressor = ghost.openDecompressor(decryptor)) {
    ByteStreams.copy(decompressor, bsOut);
  }

  assertThat(new String(bsOut.toByteArray(), UTF_8)).isEqualTo(content.get());
}
项目:nomulus    文件:ComparatorKeyringTest.java   
private static PGPPrivateKey mockPrivateKey(
    boolean altId,
    boolean altBcpgKeyFormat,
    boolean altBcpgKeyEncoded,
    boolean altPublicKeyPacketEncoded)
    throws IOException {
  String bcpgKeyFormat = altBcpgKeyFormat ? "alternate" : "bcpgFormat";
  String bcpgKeyEncoded = altBcpgKeyEncoded ? "alternate" : "bcpgEncoded";
  String publicKeyPacketEncoded = altPublicKeyPacketEncoded ? "alternate" : "packetEncoded";

  BCPGKey bcpgKey = mock(BCPGKey.class);
  PublicKeyPacket publicKeyPacket = mock(PublicKeyPacket.class);
  when(bcpgKey.getFormat()).thenReturn(bcpgKeyFormat);
  when(bcpgKey.getEncoded()).thenReturn(bcpgKeyEncoded.getBytes(UTF_8));
  when(publicKeyPacket.getEncoded()).thenReturn(publicKeyPacketEncoded.getBytes(UTF_8));
  return new PGPPrivateKey(altId ? 2 : 1, publicKeyPacket, bcpgKey);
}
项目:nexus-repository-apt    文件:AptSigningFacet.java   
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();
}
项目:Camel    文件:PGPDataFormatTest.java   
private void createSignature(OutputStream out) throws Exception {
    PGPSecretKey pgpSec = readSecretKey();
    PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(getProvider()).build(
            "sdude".toCharArray()));
    PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(pgpSec.getPublicKey().getAlgorithm(),
            HashAlgorithmTags.SHA1).setProvider(getProvider()));

    sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);

    BCPGOutputStream bOut = new BCPGOutputStream(out);

    InputStream fIn = new ByteArrayInputStream("Test Signature".getBytes("UTF-8"));

    int ch;
    while ((ch = fIn.read()) >= 0) {
        sGen.update((byte) ch);
    }

    fIn.close();

    sGen.generate().encode(bOut);

}
项目:CryptMeme    文件:JcePublicKeyDataDecryptorFactoryBuilder.java   
public PublicKeyDataDecryptorFactory build(final PGPPrivateKey privKey)
{
     return new PublicKeyDataDecryptorFactory()
     {
         public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData)
             throws PGPException
         {
             if (keyAlgorithm == PublicKeyAlgorithmTags.ECDH)
             {
                 return decryptSessionData(privKey.getPrivateKeyDataPacket(), privKey.getPublicKeyPacket(), secKeyData);
             }

             return decryptSessionData(keyAlgorithm, keyConverter.getPrivateKey(privKey), secKeyData);
         }

         public PGPDataDecryptor createDataDecryptor(boolean withIntegrityPacket, int encAlgorithm, byte[] key)
             throws PGPException
         {
             return contentHelper.createDataDecryptor(withIntegrityPacket, encAlgorithm, key);
         }
     };
}
项目:irma_future_id    文件:JcePublicKeyDataDecryptorFactoryBuilder.java   
public PublicKeyDataDecryptorFactory build(final PGPPrivateKey privKey)
{
     return new PublicKeyDataDecryptorFactory()
     {
         public byte[] recoverSessionData(int keyAlgorithm, BigInteger[] secKeyData)
             throws PGPException
         {
             return decryptSessionData(keyAlgorithm, keyConverter.getPrivateKey(privKey), secKeyData);
         }

         public PGPDataDecryptor createDataDecryptor(boolean withIntegrityPacket, int encAlgorithm, byte[] key)
             throws PGPException
         {
             return contentHelper.createDataDecryptor(withIntegrityPacket, encAlgorithm, key);
         }
     };
}
项目:appframework    文件:PGPDecryptor.java   
private static PGPPrivateKey extractPrivateKey(PGPSecretKey pgpSecKey, char[] passPhrase)
        throws PGPException {
    PGPPrivateKey privateKey = null;
    BcPGPDigestCalculatorProvider calculatorProvider = new BcPGPDigestCalculatorProvider();
    BcPBESecretKeyDecryptorBuilder secretKeyDecryptorBuilder = new BcPBESecretKeyDecryptorBuilder(
            calculatorProvider);
    PBESecretKeyDecryptor pBESecretKeyDecryptor = secretKeyDecryptorBuilder.build(passPhrase);

    try {
        privateKey = pgpSecKey.extractPrivateKey(pBESecretKeyDecryptor);
    } catch (PGPException e) {
        throw new PGPException("invalid privateKey passPhrase: " + String.valueOf(passPhrase),
                e);
    }

    return privateKey;
}
项目:bc-java    文件:JcePublicKeyDataDecryptorFactoryBuilder.java   
public PublicKeyDataDecryptorFactory build(final PGPPrivateKey privKey)
{
     return new PublicKeyDataDecryptorFactory()
     {
         public byte[] recoverSessionData(int keyAlgorithm, BigInteger[] secKeyData)
             throws PGPException
         {
             return decryptSessionData(keyAlgorithm, keyConverter.getPrivateKey(privKey), secKeyData);
         }

         public PGPDataDecryptor createDataDecryptor(boolean withIntegrityPacket, int encAlgorithm, byte[] key)
             throws PGPException
         {
             return contentHelper.createDataDecryptor(withIntegrityPacket, encAlgorithm, key);
         }
     };
}
项目:Reer    文件:PgpSignatory.java   
private PGPPrivateKey createPrivateKey(PGPSecretKey secretKey, String password) {
    try {
        PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(password.toCharArray());
        return secretKey.extractPrivateKey(decryptor);
    } catch (PGPException e) {
        throw new UncheckedException(e);
    }
}
项目:webmethods-integrationserver-pgpencryption    文件:PGPKeyReader.java   
public static PGPPrivateKey readPrivateKey(PGPSecretKey secret, char[] pass)
        throws PGPException, NoSuchProviderException {

    PGPPrivateKey key = null;
    try {
        key = secret.extractPrivateKey(pass, PGPInit.PROVIDER.getName());
    } catch (PGPException pgpe) {
        if (pgpe.getMessage().indexOf("checksum mismatch") >= 0) {
            throw new PGPException("Private key password invalid");
        } else {
            throw pgpe;
        }
    }
    return key;
}
项目:webmethods-integrationserver-pgpencryption    文件:PGPKeyReader.java   
/**
 * Returns information on a secret and private key
 * @param key A PGP private key
 * @return Key information
 */
public static String getKeyInfo(PGPPrivateKey key) {

    StringBuffer info = new StringBuffer(PGPInit.getKeyExchangeAlgorithm(key.getKey().getAlgorithm()))
        .append(" (").append(key.getKey().getFormat()).append(")")
        .append(" id:").append(key.getKeyID());

    return info.toString();
}
项目:jpgpj    文件:Subkey.java   
/**
 * Extracts the private key from this subkey's secret key
 * using the specified passphrase.
 */
protected PGPPrivateKey extractPrivateKey(String passphrase)
throws PGPException {
    if (secretKey == null) return null;
    try {
        return secretKey.extractPrivateKey(buildDecryptor(passphrase));
    } catch (PGPException e) {
        throw new PassphraseException(
            "incorrect passphrase for subkey " + this, e);
    }
}
项目:jpgpj    文件:Decryptor.java   
/**
 * Builds a symmetric-encryption decryptor for the specified passphrase.
 */
protected PublicKeyDataDecryptorFactory buildPublicKeyDecryptor(
Subkey subkey) throws PGPException {
    PGPPrivateKey privateKey = subkey.getPrivateKey();
    if (privateKey == null)
        throw new PGPException("no private key for " + subkey);
    return new BcPublicKeyDataDecryptorFactory(privateKey);
}
项目:gwt-crypto    文件:BcPGPKeyRingTest.java   
private void rewrapTest()
    throws Exception
{
    SecureRandom rand = new SecureRandom();

    // Read the secret key rings
    PGPSecretKeyRingCollection privRings = new PGPSecretKeyRingCollection(
                                                     new ByteArrayInputStream(rewrapKey), new BcKeyFingerprintCalculator());

    Iterator rIt = privRings.getKeyRings();

    if (rIt.hasNext())
    {
        PGPSecretKeyRing pgpPriv = (PGPSecretKeyRing)rIt.next();

        Iterator it = pgpPriv.getSecretKeys();

        while (it.hasNext())
        {
            PGPSecretKey pgpKey = (PGPSecretKey)it.next();

            // re-encrypt the key with an empty password
            pgpPriv = PGPSecretKeyRing.removeSecretKey(pgpPriv, pgpKey);
            pgpKey = PGPSecretKey.copyWithNewPassword(
                                pgpKey,
                                new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(rewrapPass),
                                null);
            pgpPriv = PGPSecretKeyRing.insertSecretKey(pgpPriv, pgpKey);

            // this should succeed
            PGPPrivateKey privTmp = pgpKey.extractPrivateKey(null);
        }
    }
}
项目:base    文件:PGPEncryptionUtil.java   
/**
 * 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 );
    }
}
项目:base    文件:PGPSign.java   
private static PGPSignatureGenerator getSignatureGenerator( PGPPrivateKey privateKey, BCPGOutputStream bcOut )
        throws PGPException, IOException
{
    PGPSignatureGenerator signGen = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder( privateKey.getPublicKeyPacket().getAlgorithm(), PGPUtil.SHA1 )
                    .setProvider( "BC" ) );

    signGen.init( PGPSignature.BINARY_DOCUMENT, privateKey );

    signGen.generateOnePassVersion( false ).encode( bcOut );

    return signGen;
}
项目:base    文件:PGPKeyHelper.java   
public static PGPPrivateKey readPrivateKey( InputStream is, String password ) throws PGPException, IOException
{
    PGPSecretKey secretKey = readSecretKey( is );

    return secretKey.extractPrivateKey(
            new JcePBESecretKeyDecryptorBuilder().setProvider( "BC" ).build( password.toCharArray() ) );
}
项目:base    文件:PGPKeyHelper.java   
public static PGPPrivateKey readPrivateKey( String filePath, String password ) throws PGPException, IOException
{
    PGPPrivateKey privateKey;

    try ( InputStream is = new FileInputStream( filePath ) )
    {
        privateKey = readPrivateKey( is, password );
    }

    return privateKey;
}
项目:base    文件:PGPEncryptDecryptTest.java   
@Test
public void testSuccess() throws Exception
{
    byte data[] = PGPTestDataFactory.getData();

    PGPPublicKey publicKey = PGPTestDataFactory.getPublicKey( "alice" );

    PGPPrivateKey privateKey = PGPTestDataFactory.getPrivateKey( "alice" );

    // Testing more than 10 times to be sure b/c there may be failures
    for ( int i = 1; i <= 20; i++ )
    {
        test( data, privateKey, publicKey );
    }
}
项目:base    文件:PGPEncryptDecryptTest.java   
@Test( expected = PGPException.class )
public void testFail() throws Exception
{
    PGPPublicKey publicKey = PGPTestDataFactory.getPublicKey( "bobby" );

    PGPPrivateKey privateKey = PGPTestDataFactory.getPrivateKey( "alice" );

    test( PGPTestDataFactory.getData(), privateKey, publicKey );
}
项目:base    文件:PGPSignVerifyTest.java   
@Test
public void testSuccess() throws Exception
{
    byte data[] = PGPTestDataFactory.getData();

    PGPPrivateKey privateKey = PGPTestDataFactory.getPrivateKey( "alice" );

    PGPPublicKey publicKey = PGPTestDataFactory.getPublicKey( "alice" );

    // Testing more than 10 times to be sure b/c there may be failures
    for ( int i = 1; i <= 20; i++ )
    {
        test( data, privateKey, publicKey );
    }
}
项目:base    文件:PGPSignVerifyTest.java   
private static void test( byte data[], PGPPrivateKey privateKey, PGPPublicKey publicKey ) throws Exception
{
    byte signedData[] = PGPSign.sign( data, privateKey );

    byte outData[] = PGPVerify.verify( signedData, publicKey );

    assertArrayEquals( data, outData );
}
项目:base    文件:PGPSignVerifyTest.java   
@Test( expected = PGPDataValidationException.class )
public void testFail() throws Exception
{
    PGPPrivateKey privateKey = PGPTestDataFactory.getPrivateKey( "alice" );

    // Give wrong key for validation
    PGPPublicKey publicKey = PGPTestDataFactory.getPublicKey( "bobby" );

    test( PGPTestDataFactory.getData(), privateKey, publicKey );
}
项目:base    文件:PGPKeyHelperTest.java   
@Test
public void testGetPrivateKeyFromStream() throws IOException, PGPException
{
    try ( InputStream is = new FileInputStream( PGPTestDataFactory.PRIVATE_KEY_PATH ) )
    {
        PGPPrivateKey privateKey = PGPKeyHelper.readPrivateKey( is, PGPTestDataFactory.DEFAULT_PASSWORD );

        assertNotNull( privateKey );
    }
}
项目:base    文件:PGPKeyHelperTest.java   
@Test
public void testGetPrivateKeyFromPath() throws IOException, PGPException
{
    PGPPrivateKey privateKey = PGPKeyHelper.readPrivateKey( PGPTestDataFactory.PRIVATE_KEY_PATH, PGPTestDataFactory.DEFAULT_PASSWORD );

    assertNotNull( privateKey );
}
项目:base    文件:KeyManagerImpl.java   
@Override
public PGPPrivateKey getPrivateKey( String identityId )
{

    if ( Strings.isNullOrEmpty( identityId ) )
    {
        identityId = keyData.getManHostId();
    }

    try
    {
        PGPSecretKey secretKey = getSecretKey( identityId );

        if ( secretKey != null )
        {
            return PGPEncryptionUtil.getPrivateKey( secretKey, keyData.getSecretKeyringPwd() );
        }
        else
        {
            return null;
        }
    }
    catch ( Exception ex )
    {
        LOG.error( " ***** Error getting Private key:" + ex.toString(), ex );
        return null;
    }
}