I was trying to encrypt the files with bouncy-gpg and my p12 key.
But it's getting an error No (suitable) public key for encryption to p12 email address found
Honestly, I am a newbie with a bouncy castle.
That would be appreciated with any advice.
KeyStore keystore = KeyStore.getInstance("PKCS12", "SunJSSE");
keystore.load(is, p12Password.toCharArray());
String alias = keystore.aliases().nextElement();
PrivateKey privateKey = (PrivateKey)keystore.getKey(alias, p12Password.toCharArray());
Certificate cert = keystore.getCertificate(alias);
PublicKey publicKey = cert.getPublicKey();
X509Certificate x509cert = (X509Certificate) cert;
X509Principal principal = PrincipalUtil.getSubjectX509Principal(x509cert);
Vector<?> values = principal.getValues(X509Name.EmailAddress);
String email = (String) values.get(0);
JcaPGPKeyConverter jcaPGPKeyConverter = new JcaPGPKeyConverter();
PGPPublicKey pgpPublicKey = jcaPGPKeyConverter.getPGPPublicKey(1, publicKey, new Date());
PGPPrivateKey pgpPrivateKey = jcaPGPKeyConverter.getPGPPrivateKey(pgpPublicKey, privateKey);
PGPSecretKey pgpSecretKey = new PGPSecretKey(pgpPrivateKey, pgpPublicKey, null, true, null);
final InMemoryKeyring keyring = KeyringConfigs.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(p12Password));
keyring.addPublicKey(pgpPublicKey.getEncoded());
keyring.addSecretKey(pgpSecretKey.getEncoded());
final OutputStream outputStream = BouncyGPG
.encryptToStream()
.withConfig(keyring)
.withStrongAlgorithms()
.toRecipient(email)
.andDoNotSign()
.binaryOutput()
.andWriteTo(bufferedOut);
Modified code:
hsub.setKeyFlags(false, 0xF);
PGPKeyRingGenerator gen = new PGPKeyRingGenerator(
PGPSignature.DEFAULT_CERTIFICATION,
new PGPKeyPair(pgpPublicKey, pgpPrivateKey),
'<' + email + '>',
null,
null,
null,
new JcaPGPContentSignerBuilder(pgpPublicKey.getAlgorithm(), HashAlgorithmTags.SHA1),
new JcePBESecretKeyEncryptorBuilder(SymmetricKeyAlgorithmTags.NULL).build(p12Password.toCharArray())
);
//PGPSecretKey pgpSecretKey = new PGPSecretKey(pgpPrivateKey, pgpPublicKey, null, true, null);
final InMemoryKeyring keyring = KeyringConfigs.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(p12Password));
keyring.addPublicKey(gen.generatePublicKeyRing().getEncoded());
keyring.addSecretKey(gen.generateSecretKeyRing().getEncoded());
try (
final InputStream cipherTextStream = Files.newInputStream(sourceFile);
final OutputStream fileOutput = Files.newOutputStream(destFile);
final BufferedOutputStream bufferedOut = new BufferedOutputStream(fileOutput, BUFFERSIZE);
final InputStream plaintextStream = BouncyGPG
.decryptAndVerifyStream()
.withConfig(keyring)
.andValidateSomeoneSigned()
.fromEncryptedInputStream(cipherTextStream)