1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
|
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Iterator;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataList;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPObjectFactory;
import org.bouncycastle.openpgp.PGPOnePassSignatureList;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPUtil;
public class PGPCryptography {
static private final Logger logger = Logger.getLogger(PGPCryptography.class);
static {
Security.addProvider(new BouncyCastleProvider());
}
public PGPCryptography() throws Exception {
}
public void listPublicKeys(File publicKeyFile) throws Exception{
if(publicKeyFile == null || !publicKeyFile.exists()){
throw new IllegalArgumentException("publicKeyFile cannot be null and must be an existing file");
}
try {
InputStream in = new FileInputStream(publicKeyFile);
PGPPublicKeyRing publicKeyRing = new PGPPublicKeyRing(in);
Iterator it = publicKeyRing.getPublicKeys();
while(it.hasNext()){
PGPPublicKey k = (PGPPublicKey) it.next();
ToStringBuilder b = new ToStringBuilder(k);
b.append("isMasterKey", k.isMasterKey());
b.append("isEncryptionKey", k.isEncryptionKey());
b.append("isRevoked", k.isRevoked());
String userids = "";
Iterator useridIt = k.getUserIDs();
while(useridIt.hasNext()){
String uid = (String) useridIt.next();
if(userids.length() > 0){
userids += ", ";
}
userids += uid;
}
b.append("userids", userids);
logger.info(b);
}
} catch (Throwable e) {
throw new Exception(e);
}
}
public File encrypt(File publicKeyFile, String userid, File sourceFile) throws Exception {
if(publicKeyFile == null || !publicKeyFile.exists()){
throw new IllegalArgumentException("publicKeyFile cannot be null and must be an existing file");
}
if(sourceFile == null || !sourceFile.exists()){
throw new IllegalArgumentException("sourceFile cannot be null and must be an existing file");
}
logger.debug("About to encrypt content of file: " + sourceFile.getName());
try {
File encryptedFile = File.createTempFile("pgp_", ".encrypted", new File("C:\\pgp\\decryptedfile\\"));
FileOutputStream fileOut = new FileOutputStream(encryptedFile);
PGPPublicKey publicKey = findPublicKey(publicKeyFile, userid, true);
if(publicKey == null){
throw new IllegalArgumentException("no public key for " + userid + " in keyring " + publicKeyFile);
}
ArmoredOutputStream armoredOut = new ArmoredOutputStream(fileOut);
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator compressedData = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
PGPUtil.writeFileToLiteralData(compressedData.open(byteArrayOut), PGPLiteralData.BINARY, sourceFile);
compressedData.close();
PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(PGPEncryptedDataGenerator.CAST5, new SecureRandom(), "BC");
encryptedDataGenerator.addMethod(publicKey);
byte[] bytes = byteArrayOut.toByteArray();
OutputStream encryptedOut = encryptedDataGenerator.open(armoredOut, bytes.length);
encryptedOut.write(bytes);
encryptedDataGenerator.close();
armoredOut.close();
fileOut.close();
logger.debug("file was encrypted : " + sourceFile.getName());
return encryptedFile;
} catch (Exception e) {
logger.error("Encrypt exception ", e);
throw new Exception(e);
}
}
public File decrypt(File privateKeyFile, String privateKeyPassword, File encryptedFile) throws Exception {
File decryptedFile = null;
if(privateKeyFile == null || !privateKeyFile.exists()){
throw new IllegalArgumentException("privateKeyFile cannot be null and must be an existing file");
}
if(encryptedFile == null || !encryptedFile.exists()){
throw new IllegalArgumentException("encryptedFile cannot be null and must be an existing file");
}
try {
InputStream encryptedFileIn = new FileInputStream(encryptedFile);
InputStream privateKeyIn = new FileInputStream(privateKeyFile);
decryptedFile = File.createTempFile("pgp_", ".decrypted");
logger.debug("About to decrypt content of file: " + decryptedFile.getName());
FileOutputStream out = new FileOutputStream(decryptedFile);
logger.debug("decrypting content of " + encryptedFile.getName() + " to " + decryptedFile.getName());
encryptedFileIn = PGPUtil.getDecoderStream(encryptedFileIn);
PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(encryptedFileIn);
PGPEncryptedDataList encryptedDataList;
Object pgpObject = pgpObjectFactory.nextObject();
if (pgpObject instanceof PGPEncryptedDataList) {
encryptedDataList = (PGPEncryptedDataList) pgpObject;
} else {
encryptedDataList = (PGPEncryptedDataList) pgpObjectFactory.nextObject();
}
Iterator encryptedDataListIt = encryptedDataList.getEncryptedDataObjects();
PGPPrivateKey privateKey = null;
PGPPublicKeyEncryptedData privateKeyEncryptedData = null;
while (privateKey == null && encryptedDataListIt.hasNext()) {
privateKeyEncryptedData = (PGPPublicKeyEncryptedData) encryptedDataListIt.next();
privateKey = findSecretKey(privateKeyIn, privateKeyEncryptedData.getKeyID(), privateKeyPassword.toCharArray());
}
if (privateKey == null){
encryptedFileIn.close();
privateKeyIn.close();
throw new IllegalStateException("no private key could be found");
}
InputStream clear = privateKeyEncryptedData.getDataStream(privateKey, "BC");
PGPObjectFactory plainFact = new PGPObjectFactory(clear);
Object thing = plainFact.nextObject();
Object message = null;
if (thing instanceof PGPLiteralData) {
message = thing;
} else if (thing instanceof PGPCompressedData) {
PGPCompressedData cData = (PGPCompressedData) thing;
InputStream compressedStream = new BufferedInputStream(cData.getDataStream());
PGPObjectFactory pgpFact = new PGPObjectFactory(compressedStream);
message = pgpFact.nextObject();
if (message instanceof PGPOnePassSignatureList) {
message = pgpFact.nextObject();
}
}
if (message instanceof PGPLiteralData) {
// decrypt as normal
PGPLiteralData literal = (PGPLiteralData) message;
BufferedReader w = new BufferedReader(new InputStreamReader(literal.getInputStream()));
String s = null;
while((s = w.readLine()) != null){
//logger.debug("decrypted: " + s);
out.write(s.getBytes());
}
} else {
logger.error("message type " + message.toString() + " not supported.");
return null;
}
if (privateKeyEncryptedData.isIntegrityProtected()) {
if (!privateKeyEncryptedData.verify()) {
logger.error("message failed integrity check");
return null;
}
}
out.close();
encryptedFileIn.close();
privateKeyIn.close();
return decryptedFile;
} catch (Exception e) {
if(decryptedFile != null){
decryptedFile.delete();
}
logger.error("An error occured during PGP decryption: \n", e);
throw new Exception(e);
}
}
public PGPPublicKey findPublicKey(File publicKeyFile, String userid, boolean encryption) throws IOException, PGPException {
PGPPublicKeyRingCollection publicKeyRingCollection = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(new FileInputStream(publicKeyFile)));
Iterator keyRingIt = publicKeyRingCollection.getKeyRings();
while (keyRingIt.hasNext()) {
PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIt.next();
Iterator keysIt = keyRing.getPublicKeys();
while (keysIt.hasNext()) {
PGPPublicKey key = (PGPPublicKey) keysIt.next();
Iterator userIt = key.getUserIDs();
while(userIt.hasNext()){
String user = (String) userIt.next();
if(user.equalsIgnoreCase(userid) && key.isEncryptionKey() == encryption){
return key;
}
}
}
}
return null;
}
private PGPPrivateKey findSecretKey(InputStream privateKeyIn, long privateKeyID, char[] password) throws IOException, PGPException, NoSuchProviderException {
PGPSecretKeyRingCollection secretKeyRingCollection = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(privateKeyIn));
PGPSecretKey secretKey = secretKeyRingCollection.getSecretKey(privateKeyID);
if (secretKey == null) {
return null;
}
return secretKey.extractPrivateKey(password, "BC");
}
} |