Skip to content

Instantly share code, notes, and snippets.

@jordanbaucke
Created July 26, 2014 14:23
Show Gist options
  • Save jordanbaucke/7bf8ea4106b3e00307ba to your computer and use it in GitHub Desktop.
Save jordanbaucke/7bf8ea4106b3e00307ba to your computer and use it in GitHub Desktop.
private static String signMessageByteArray(String message,
PGPSecretKey pgpSec, char pass[]) throws IOException,
NoSuchAlgorithmException, NoSuchProviderException, PGPException,
SignatureException {
byte[] messageCharArray = message.getBytes();
ByteArrayOutputStream encOut = new ByteArrayOutputStream();
OutputStream out = encOut;
out = new ArmoredOutputStream(out);
// Unlock the private key using the password
PGPPrivateKey pgpPrivKey = pgpSec
.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder()
.setProvider("BC").build(pass));
// Signature generator, we can generate the public key from the private key! Nifty!
PGPSignatureGenerator sGen = new PGPSignatureGenerator(
new JcaPGPContentSignerBuilder(pgpSec.getPublicKey()
.getAlgorithm(), PGPUtil.SHA1).setProvider("BC"));
sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);
Iterator it = pgpSec.getPublicKey().getUserIDs();
if (it.hasNext()) {
PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
spGen.setSignerUserID(false, (String) it.next());
sGen.setHashedSubpackets(spGen.generate());
}
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(
PGPCompressedData.ZLIB);
BCPGOutputStream bOut = new BCPGOutputStream(comData.open(out));
sGen.generateOnePassVersion(false).encode(bOut);
PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY,
PGPLiteralData.CONSOLE, messageCharArray.length, new Date());
for (byte c : messageCharArray) {
lOut.write(c);
sGen.update(c);
}
lOut.close();
lGen.close();
sGen.generate().encode(bOut);
comData.close();
out.close();
return encOut.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment