org.bouncycastle.openpgp.operator.PGPDigestCalculator Java Examples

The following examples show how to use org.bouncycastle.openpgp.operator.PGPDigestCalculator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PGPUtils.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
public static PGPSecretKeyRing copySecretKeyRingWithNewPassword(byte[] privateKeyData,
        char[] oldPassphrase, char[] newPassphrase) throws PGPException, IOException, KonException {

    // load the secret key ring
    PGPSecretKeyRing secRing = new PGPSecretKeyRing(privateKeyData, FP_CALC);

    PGPDigestCalculatorProvider calcProv = new JcaPGPDigestCalculatorProviderBuilder().build();
    PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder(calcProv)
        .setProvider(PGPUtils.PROVIDER)
        .build(oldPassphrase);

    PGPDigestCalculator calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA256);
    PBESecretKeyEncryptor encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calc)
        .setProvider(PROVIDER).build(newPassphrase);

    try {
        return PGPSecretKeyRing.copyWithNewPassword(secRing, decryptor, encryptor);
    } catch (PGPException ex) {
        // treat this special, cause most like the decryption password was wrong
        throw new KonException(KonException.Error.CHANGE_PASS_COPY, ex);
    }
}
 
Example #2
Source File: KeyGeneratorServicePgpImpl.java    From pgptool with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Key createNewKey(CreateKeyParams params) throws FieldValidationException {
	try {
		Preconditions.checkArgument(params != null, "params must not be null");
		assertParamsValid(params);

		// Create Master key
		KeyPair masterKey = getOrGenerateKeyPair(getMasterKeyParameters());
		PGPKeyPair masterKeyBc = new JcaPGPKeyPair(algorithmNameToTag(masterKeyPurpose), masterKey, new Date());
		BcPGPContentSignerBuilder keySignerBuilderBc = new BcPGPContentSignerBuilder(
				algorithmNameToTag(masterKeyPurpose), hashAlgorithmNameToTag(masterKeySignerHashingAlgorithm));

		// Setup seret key encryption
		PGPDigestCalculator digestCalc = new BcPGPDigestCalculatorProvider()
				.get(hashAlgorithmNameToTag(secretKeyHashingAlgorithm));
		BcPBESecretKeyEncryptorBuilder encryptorBuilderBC = new BcPBESecretKeyEncryptorBuilder(
				symmetricKeyAlgorithmNameToTag(secretKeyEncryptionAlgorithm), digestCalc);
		PBESecretKeyEncryptor keyEncryptorBc = encryptorBuilderBC.build(params.getPassphrase().toCharArray());

		// Key pair generator
		String userName = params.getFullName() + " <" + params.getEmail() + ">";
		PGPKeyRingGenerator keyPairGeneratorBc = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION,
				masterKeyBc, userName, digestCalc, null, null, keySignerBuilderBc, keyEncryptorBc);

		// Add Sub-key for encryption
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(encryptionKeyAlgorithm, PROVIDER);
		if ("ELGAMAL".equals(encryptionKeyAlgorithm)) {
			keyPairGenerator.initialize(new DHParameterSpec(dhParamsPrimeModulus, dhParamsBaseGenerator));
		} else if ("RSA".equals(encryptionKeyAlgorithm)) {
			// Re-using master key size.
			keyPairGenerator.initialize(new RSAKeyGenParameterSpec(masterKeySize, RSAKeyGenParameterSpec.F4));
		} else {
			throw new IllegalArgumentException(
					"Hanlding of parameter creation for " + encryptionKeyAlgorithm + " is not implemented");
		}
		KeyPair encryptionSubKey = keyPairGenerator.generateKeyPair();
		PGPKeyPair encryptionSubKeyBc = new JcaPGPKeyPair(algorithmNameToTag(encryptionKeyPurpose),
				encryptionSubKey, new Date());
		keyPairGeneratorBc.addSubKey(encryptionSubKeyBc);

		// TBD-191: Also add a sub-key for signing
		// KeyPair signatureSubKey = keyPairGenerator.generateKeyPair();
		// PGPKeyPair signatureSubKeyBc = new
		// TBD-191: RSA_SIGN must not be hardcoded
		// JcaPGPKeyPair(algorithmNameToTag("RSA_SIGN"), signatureSubKey,
		// new Date());
		// keyPairGeneratorBc.addSubKey(signatureSubKeyBc);

		// building ret
		return buildKey(keyPairGeneratorBc);
	} catch (Throwable t) {
		Throwables.throwIfInstanceOf(t, FieldValidationException.class);
		throw new RuntimeException("Failed to generate key", t);
	}
}
 
Example #3
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 4 votes vote down vote up
private static PGPKeyRingGenerator generateKeyRingGenerator( String id, char[] pass, int s2kcount, int keySize,
                                                             KeyPair keyPair ) throws PGPException
{
    // This object generates individual key-pairs.
    RSAKeyPairGenerator kpg = new RSAKeyPairGenerator();

    // Boilerplate RSA parameters, no need to change anything
    // except for the RSA key-size (2048). You can use whatever
    // key-size makes sense for you -- 4096, etc.
    kpg.init( new RSAKeyGenerationParameters( BigInteger.valueOf( 0x10001 ), new SecureRandom(), keySize, 12 ) );

    // First create the master (signing) key with the generator.
    PGPKeyPair rsakp_sign = new BcPGPKeyPair( PGPPublicKey.RSA_GENERAL, kpg.generateKeyPair(), new Date() );
    // Then an encryption subkey.
    PGPKeyPair rsakp_enc = new BcPGPKeyPair( PGPPublicKey.RSA_GENERAL, kpg.generateKeyPair(), new Date() );

    keyPair.setPrimaryKeyId( Long.toHexString( rsakp_sign.getKeyID() ) );
    keyPair.setPrimaryKeyFingerprint( BytesToHex( rsakp_sign.getPublicKey().getFingerprint() ) );
    keyPair.setSubKeyId( Long.toHexString( rsakp_enc.getKeyID() ) );
    keyPair.setSubKeyFingerprint( BytesToHex( rsakp_enc.getPublicKey().getFingerprint() ) );

    // Add a self-signature on the id
    PGPSignatureSubpacketGenerator signhashgen = new PGPSignatureSubpacketGenerator();

    // Add signed metadata on the signature.
    // 1) Declare its purpose
    signhashgen.setKeyFlags( false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER );
    // 2) Set preferences for secondary crypto algorithms to use
    //    when sending messages to this key.
    signhashgen.setPreferredSymmetricAlgorithms( false, new int[] {
            SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128,
            SymmetricKeyAlgorithmTags.CAST5, SymmetricKeyAlgorithmTags.TRIPLE_DES
    } );
    signhashgen.setPreferredHashAlgorithms( false, new int[] {
            HashAlgorithmTags.SHA256, HashAlgorithmTags.SHA1, HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA512,
            HashAlgorithmTags.SHA224,
    } );
    signhashgen.setPreferredCompressionAlgorithms( false, new int[] {
            CompressionAlgorithmTags.ZLIB, CompressionAlgorithmTags.BZIP2, CompressionAlgorithmTags.ZIP
    } );
    // 3) Request senders add additional checksums to the
    //    message (useful when verifying unsigned messages.)
    signhashgen.setFeature( false, Features.FEATURE_MODIFICATION_DETECTION );

    // Create a signature on the encryption subkey.
    PGPSignatureSubpacketGenerator enchashgen = new PGPSignatureSubpacketGenerator();
    // Add metadata to declare its purpose
    enchashgen.setKeyFlags( false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE );

    // Objects used to encrypt the secret key.
    PGPDigestCalculator sha1Calc = new BcPGPDigestCalculatorProvider().get( HashAlgorithmTags.SHA1 );

    // bcpg 1.48 exposes this API that includes s2kcount. Earlier
    // versions use a default of 0x60.
    PBESecretKeyEncryptor pske =
            ( new BcPBESecretKeyEncryptorBuilder( PGPEncryptedData.CAST5, sha1Calc, s2kcount ) ).build( pass );
    // Finally, create the keyring itself. The constructor
    // takes parameters that allow it to generate the self
    // signature.
    PGPKeyRingGenerator keyRingGen =
            new PGPKeyRingGenerator( PGPSignature.POSITIVE_CERTIFICATION, rsakp_sign, id, sha1Calc,
                    signhashgen.generate(), null,
                    new BcPGPContentSignerBuilder( rsakp_sign.getPublicKey().getAlgorithm(),
                            HashAlgorithmTags.SHA1 ), pske );

    // Add our encryption subkey, together with its signature.
    keyRingGen.addSubKey( rsakp_enc, enchashgen.generate(), null );
    return keyRingGen;
}