How to decrypt a signed pgp encrypted file? - java

How can I decrypt and verify a file encrypted with PGP with the BouncyCastle Java API?

Encryption Code:
private static void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey, PGPSecretKey pgpSec, boolean armor, boolean withIntegrityCheck, char[] pass) throws IOException, NoSuchProviderException {
if (armor) {
out = new ArmoredOutputStream(out);
}
try {
PGPEncryptedDataGenerator encGen =
new PGPEncryptedDataGenerator(
new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5).setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(
new SecureRandom())
.setProvider("BC"));
encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider("BC"));
OutputStream encryptedOut = encGen.open(out, new byte[BUFFER_SIZE]);
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
OutputStream compressedData = comData.open(encryptedOut);
//OutputStream compressedData = encryptedOut;
PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(
new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(pass));
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());
}
//BCPGOutputStream bOut = new BCPGOutputStream(compressedData);
sGen.generateOnePassVersion(false).encode(compressedData); // bOut
File file = new File(fileName);
PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
OutputStream lOut = lGen.open(compressedData, PGPLiteralData.BINARY, file.getName(), new Date(),
new byte[BUFFER_SIZE]); //bOut
FileInputStream fIn = new FileInputStream(file);
int ch;
while ((ch = fIn.read()) >= 0) {
lOut.write(ch);
sGen.update((byte) ch);
}
fIn.close();
lOut.close();
lGen.close();
sGen.generate().encode(compressedData);
//bOut.close();
comData.close();
compressedData.close();
encryptedOut.close();
encGen.close();
if (armor) {
out.close();
}
} catch (PGPException e) {
System.err.println(e);
if (e.getUnderlyingException() != null) {
e.getUnderlyingException().printStackTrace();
}
} catch (SignatureException e) {
System.err.println(e);
}
}
Decryption Code:
public static void decryptFile(InputStream in, InputStream keyIn, char[] passwd, OutputStream fOut, InputStream publicKeyIn) throws IOException, NoSuchProviderException, SignatureException,
PGPException {
in = PGPUtil.getDecoderStream(in);
PGPObjectFactory pgpF = new PGPObjectFactory(in);
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
//
// the first object might be a PGP marker packet.
//
if (o instanceof PGPEncryptedDataList) {
enc = (PGPEncryptedDataList) o;
} else {
enc = (PGPEncryptedDataList) pgpF.nextObject();
}
//
// find the secret key
//
Iterator<?> it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn));
while (sKey == null && it.hasNext()) {
pbe = (PGPPublicKeyEncryptedData) it.next();
sKey = PGPTools.findSecretKey(pgpSec, pbe.getKeyID(), passwd);
}
if (sKey == null) {
throw new IllegalArgumentException("secret key for message not found.");
}
InputStream clear = pbe.getDataStream(
new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey));
PGPObjectFactory plainFact = new PGPObjectFactory(clear);
Object message = null;
PGPOnePassSignatureList onePassSignatureList = null;
PGPSignatureList signatureList = null;
PGPCompressedData compressedData = null;
message = plainFact.nextObject();
ByteArrayOutputStream actualOutput = new ByteArrayOutputStream();
while (message != null) {
log.trace(message.toString());
if (message instanceof PGPCompressedData) {
compressedData = (PGPCompressedData) message;
plainFact = new PGPObjectFactory(compressedData.getDataStream());
message = plainFact.nextObject();
}
if (message instanceof PGPLiteralData) {
// have to read it and keep it somewhere.
Streams.pipeAll(((PGPLiteralData) message).getInputStream(), actualOutput);
} else if (message instanceof PGPOnePassSignatureList) {
onePassSignatureList = (PGPOnePassSignatureList) message;
} else if (message instanceof PGPSignatureList) {
signatureList = (PGPSignatureList) message;
} else {
throw new PGPException("message unknown message type.");
}
message = plainFact.nextObject();
}
actualOutput.close();
PGPPublicKey publicKey = null;
byte[] output = actualOutput.toByteArray();
if (onePassSignatureList == null || signatureList == null) {
throw new PGPException("Poor PGP. Signatures not found.");
} else {
for (int i = 0; i < onePassSignatureList.size(); i++) {
PGPOnePassSignature ops = onePassSignatureList.get(0);
log.trace("verifier : " + ops.getKeyID());
PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(
PGPUtil.getDecoderStream(publicKeyIn));
publicKey = pgpRing.getPublicKey(ops.getKeyID());
if (publicKey != null) {
ops.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey);
ops.update(output);
PGPSignature signature = signatureList.get(i);
if (ops.verify(signature)) {
Iterator<?> userIds = publicKey.getUserIDs();
while (userIds.hasNext()) {
String userId = (String) userIds.next();
log.trace("Signed by {}", userId);
}
log.trace("Signature verified");
} else {
throw new SignatureException("Signature verification failed");
}
}
}
}
if (pbe.isIntegrityProtected() && !pbe.verify()) {
throw new PGPException("Data is integrity protected but integrity is lost.");
} else if (publicKey == null) {
throw new SignatureException("Signature not found");
} else {
fOut.write(output);
fOut.flush();
fOut.close();
}
}
For reference, this is what PGPTools.findSecretKey does:
public static PGPPrivateKey findSecretKey(InputStream keyIn, long keyID, char[] pass)
throws IOException, PGPException {
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn));
PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
if (pgpSecKey == null) return null;
PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass);
return pgpSecKey.extractPrivateKey(decryptor);
}

I had the same problem by looking around the BouncyCastle examples.
My goal was to make two methods in a service like:
decryptAndVerify( InputStream, PGPPublicKey, PGPPrivateKey, Passphrase)
signAndEncrypt( InputStream, OutputStream, PGPPrivateKey, PGPPublicKey, Passphrase )
For the first method:
I mixed the verifyFile from this sample
and with the decryptFile here
For the second method I took example from this blog.

Related

How to Extract PGP public key and PGP Private key from JKS File and to Decrypt a pgp Encrypted Message?

I have the following code for decrypting a PGP encrypted Private Key Message.
KeyStore ks = KeyStore.getInstance("JKS");
File file = new file("abc.txt");
ks.load(new FileInputStream("abc.jks"), "******".toCharArray());
KeyStore.PrivateKeyEntry keyEntry =(KeyStore.PrivateKeyEntry) ks.getEntry("abcd", new KeyStore.PasswordProtection("******".toCharArray()));
PrivateKey k = keyEntry.getPrivateKey();
CertificateFactory fact = CertificateFactory.getInstance("X.509");
FileInputStream is = new FileInputStream ("ght.cer");
X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
PublicKey NPCIPubKey = cer.getPublicKey();
byte[] bt = new byte[(int)file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bt);
PGPPublicKey pk1 = new JcaPGPKeyConverter().getPGPPublicKey(PGPPublicKey.RSA_GENERAL, NPCIPubKey, new Date());
PGPPrivateKey prik = new JcaPGPKeyConverter().getPGPPrivateKey(pk1, k);
DecClass dec = new DecClass();
dec.rsaDecryptFile(fis,prik);'
Decryption Class :
public class DecClass {
public void rsaDecryptFile(InputStream in, PGPPrivateKey priK) {
try {
Security.addProvider(new BouncyCastleProvider());
in = org.bouncycastle.openpgp.PGPUtil.getDecoderStream(in);
PGPObjectFactory pgpF = new PGPObjectFactory(in);
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
//
// the first object might be a PGP marker packet.
//
if (o instanceof PGPEncryptedDataList) {
enc = (PGPEncryptedDataList) o;
} else {
enc = (PGPEncryptedDataList) pgpF.nextObject();
}
Iterator<PGPPublicKeyEncryptedData> it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
while (sKey == null && it.hasNext()) {
pbe = it.next();
sKey = priK;
}
if (sKey == null) {
throw new IllegalArgumentException("Secret key for message not found.");
}
PublicKeyDataDecryptorFactory b = new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC")
.setContentProvider("BC").build(sKey);
InputStream clear = pbe.getDataStream(b);
PGPObjectFactory plainFact = new PGPObjectFactory(clear,new BcKeyFingerprintCalculator());
Object message = plainFact.nextObject();
System.out.println("Secret key info 3:: " + pbe.getKeyID() + new Date());
if (message instanceof PGPCompressedData) {
PGPCompressedData cData = (PGPCompressedData) message;
PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream(),new BcKeyFingerprintCalculator());
message = pgpFact.nextObject();
}
if (message instanceof PGPLiteralData) {
PGPLiteralData ld = (PGPLiteralData) message;
InputStream unc = ld.getInputStream();
int ch;
FileUtils.copyInputStreamToFile(unc, new File("D:\\Development_Docs\\PGP\\Bulk\\target.txt"));
} else if (message instanceof PGPOnePassSignatureList) {
throw new PGPException("Encrypted message contains a signed message - not literal data.");
} else {
throw new PGPException("Message is not a simple encrypted file - type unknown.");
}if (pbe.isIntegrityProtected()) {
if (!pbe.verify()) {
throw new PGPException("Message failed integrity check");
}
}
}catch (PGPException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
}
But am getting null pointer exception in Iterator<PGPPublicKeyEncryptedData> it = enc.getEncryptedDataObjects(); line in DecClass rsaDecryptFile Method.While debugging value of PGPEncryptedDataList enc is coming null. Am not able to trace the source of the exception. Please advise on how can i resolve this exception and get the code to work. Please find below snippet of my input encrypted message
-----BEGIN PGP MESSAGE-----
Version: BCPG v1.47
hQEMAxVcH36ac1ahAQf/UMvfmBxIEtGOcIzovhcQ8WTojB06oF8/8i5lv6iz3EEj
vIceEWSHdeCJuYSemPaiIrccOOfGFqZodg6a7IQhjG0WcuSg5F4a/Pn/7KxKqB9n
OoHwmpX0+Pbm1Y2mNAj3LN9KtK3
-----END PGP MESSAGE-----
I'm able to decrypt the file by modifing the following code.Hope it'll work for you.
#SuppressWarnings({ "unchecked", "unused" })
public static void rsaDecryptFile(InputStream in, OutputStream out,
PGPPrivateKey priK) {
try {
Security.addProvider(new BouncyCastleProvider());
in = org.bouncycastle.openpgp.PGPUtil.getDecoderStream(in);
PGPObjectFactory pgpF = new PGPObjectFactory(in,new
JcaKeyFingerprintCalculator());
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
//
// the first object might be a PGP marker packet.
//
if (o instanceof PGPEncryptedDataList) {
enc = (PGPEncryptedDataList) o;
} else {
enc = (PGPEncryptedDataList) pgpF.nextObject();
}
//
// find the secret key
//
//Iterator<PGPPublicKeyEncryptedData> it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
while (sKey == null /*&& it.hasNext()*/) {
//pbe = it.next();
pbe = (PGPPublicKeyEncryptedData)enc.getEncryptedDataObjects().next();
//sKey = findSecretKey(pubK, pbe.getKeyID(), priK);
sKey = priK;
}
if (sKey == null) throw new IllegalArgumentException("Secret key for message not found.");
PublicKeyDataDecryptorFactory b = new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC")
.setContentProvider("BC").build(sKey);
InputStream clear = pbe.getDataStream(b);
PGPObjectFactory plainFact = new PGPObjectFactory(clear,new JcaKeyFingerprintCalculator());
Object message = plainFact.nextObject();
System.out.println("Secret key info 3:: " + pbe.getKeyID() + new Date());
if (message instanceof PGPCompressedData) {
PGPCompressedData cData = (PGPCompressedData) message;
PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream(),new JcaKeyFingerprintCalculator());
message = pgpFact.nextObject();
}
if (message instanceof PGPLiteralData) {
PGPLiteralData ld = (PGPLiteralData) message;
InputStream unc = ld.getInputStream();
System.out.println("Unc d " + unc.read());
int ch;
while ((ch = unc.read()) >= 0) {
out.write(ch);
}
//FileUtils.copyInputStreamToFile(unc, new File("D:\\Development_Docs\\PGP\\Bulk\\target.txt"));
} else if (message instanceof PGPOnePassSignatureList) {
throw new PGPException("Encrypted message contains a signed message - not literal data.");
} else {
throw new PGPException("Message is not a simple encrypted file - type unknown.");
}
if (pbe.isIntegrityProtected()) {
if (!pbe.verify()) {
throw new PGPException("Message failed integrity check");
}
}
}catch (PGPException e) {
// TODO: handle exception
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}

Android RSA decryption using private key, non-sense result

I am doing RSA decryption in my Android project, and somehow the result makes non-sense. I am showing my code here:
private static final int MAX_DECRYPT_BLOCK = 256;
private static RSAPrivateKey loadPrivateKey(InputStream in) throws Exception {
RSAPrivateKey priKey;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
byte[] priKeyData = Base64.decode(new String(sb), Base64.NO_WRAP);
PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(priKeyData);
KeyFactory keyFactory= KeyFactory.getInstance("RSA",new BouncyCastleProvider());
priKey= (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (IOException e) {
throw new Exception("error reading the key");
} catch (NullPointerException e) {
throw new Exception("inputstream is null");
}
return priKey;
}
/**
* decrypt with a private key
*
* #param privateKey
* #param cipherData
* #return
* #throws Exception
*/
private static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
if (privateKey == null) {
throw new Exception("key is null");
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int inputLen = cipherData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(cipherData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(cipherData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
} catch (NoSuchAlgorithmException e) {
throw new Exception("no such algorithm");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("InvalidKeyException");
} catch (IllegalBlockSizeException e) {
throw new Exception("IllegalBlockSizeException");
} catch (BadPaddingException e) {
throw new Exception("BadPaddingException");
}
}
public static String RSADecrypt(Context context, String KeyFileNameInAssetFolder, byte[] content) {
try {
InputStream inputStream = context.getResources().getAssets().open(KeyFileNameInAssetFolder);
RSAPrivateKey privateKey = loadPrivateKey(inputStream);
byte[] b = decrypt(privateKey, content);
return new String(b,"utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
and I am calling with this statement:
String result = RSAUtils.RSADecrypt(getApplicationContext(), Constant.PRIVATE_KEY_PKCS8_FILE_NAME,Base64.decode(qrcode_result,Base64.NO_WRAP));
And this is the private key:
> -----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCsQTbkXviKG1od
wVp0t15JB4OkdDUo8O36/yzLoJmsmPf3yFzAJ3YzEAaWAKKpUx92c9yfW4vW849F
pno/GUJLwPkIG5ss1YR55P5UI76kpLM74ZXume9+WfEuQ3B/HHkcnmCVl4CV/Xqq
4X4d3Rc7zGTbGSHdVui1QJ5ubQoqHjSGaO9j2SvMsqDSU20S1DjrL/8sb0e7B63a
fJVzOZFi7E62zqYzfBOEupY+24Ac8i7s8tyX3Bd4OJ1zdQ+si5yeIkaRiD8ZeUbJ
3yS2MlUohvuwmJy7uxpP8mYXmaXM1ZtMFLaLRUc4leA7KDRlDXHJLSYAkFxCyw8J
RTK2QOcTAgMBAAECggEARRrUnsHLC/z1JkLPu0tlM/8jvPIx8X7Wun9sxTRk8m1b
7bggHaa3ML0ZJ0yR9UQ3txm8ROJBM7b6n4KuQGotwp5kSfBpTI9MWmqX7cF5ViwN
C9TwhYyUHCiRLXI4y4XswKJ5NQpWt9W9RJi6M9ji3Uaen5dxko6vRSfrZ3mvPj2/
blW5HV8j3RIzJ3942CzQw2IX/hQWhityFxTwGY3f3Rh05jpI+SowJlOTIheOHqlR
2VFTLTYIvmoZJduFzxlM4t5W3VzGZl/KmC1apNh2N3xPcmimq/YsrDqN5GgkNhuh
/WTTB7pa3qsQlFPKnwylLc2LviQafiR+yunolImCwQKBgQDS9TIth96x+McD2Gu7
1QQlalhDK1+s/O9rjQV4la9FykEFdJB7+Q9xyq9vIqqSVIFj8rI1wqziHp3czUkY
Ijqcgp0DB1Stbwp3DPh3Rq4zVHHnKplzhMwAaDBOVaHmEGaiyB/LwspCcDoON+i+
70Bzdc6EW/KqNpGlP3OPJT2pSwKBgQDRCIlyklOnKQnzbCaMwFkBZBJlHHqgIl1Z
S7jdFaTX7uUkbXF3WVtJlY1+r6h0rK075hX/61VlhfoFjBIR/7ZDaBkrH3Nd6cdU
PJIOgnQEYobRAF4ugWSPTsf0A6bjd7tsVZ7+1ediKwg1QY9Pk2hj/jRb0FD2nKZ+
yWI3RPekWQKBgBM1DfeFSmpr2zrnZo+4imMZtqWO+mwWr3ncYiYjgszY6Gilv036
VESpDqYQwvUFyq4d98nbSsBfx0HGUyRmYW3EmqUe8r/Dv3EtdiXuAohb5O8GOuiA
q85RrixDsbTvw1iI3hRATQgVjcOjpYZU5Epe7ImykXqb81DXYR8kZePXAoGBAJWk
CuFeJ0yPcHQ2hBJW0GDShuijTpW8hB8cuiZrDCsY9ijxwDy0V0mCKlz62xlLVGiA
+lbO3b9j/exirbz81jnDF+FrDme4p92Bzv1cHjnVXrXYEZQxRQ/iUfo5cwt790xC
ryO3dYEtVR7q4/EPkbejj0/6/TrOQdKZ0BnI4Y9hAoGBALlFBlvCRspXYBOXf0XM
5V0Q4t1vAxgcfNaKi4h612UZDF2GluYIwtuF+uJlxYvhRxq1gzmgP5+Z9gblMb6d
8ysWfWPl2RWGYNw0nwOYhWI1/cWRNpfH7W+OY2kHmB3G1bHnf5PxUb+1JL2PvfXS
fZ8JY1/xKqYSoSORJYQh2Z7D
-----END PRIVATE KEY-----
and this is the string I tried to decrypt:
JRhdX3DLGbMVcxN6jV3697yUkfZUBfz/ee6P8pGlgHFnOo5OWgXH0fc10Ps4li3UKkyVqo1+iz10/zzhjVTbSKC5Fai6dLnQgrFVz6lOqOeR83+x4ezyF75kORdgAyEp5MiW0LHsK13ryYEqZ1GHiZdJ6E54nbLZsZGKJJkRZ2OVQW9hovqBQXAP3M8dGk1liruiY+xAHfKkeS73m+IPYPTNGQT+y5IDACoq8dLUvV4nw76p2ZUfyYFgoYOir9KBN2SbfcndR71DZUPWdRnZoDLNFCfvMjC2Ui27j3CxcQLzJSt4K4K+kmU6n5t8Xb6YyGb2j+5pduXcnZMgc5cjsm6NBIXUv+DQzXeRo61vHrXKWeamJ+Whl0RnA9HjIl6medxfE64xHgF+aD6lqbQcwWwHWm/s3f5XkS0xP21bYuOt8mgmHC90qhJNRGKmTGgyxxls/18aV4eZEIRUg82wCIXavvQGLA3hk5UWl4YkrpaGYh+SX1t3yfi+wQ8f30lQBrKl4A0iKk4WHKNCka6nd3sc8bDwD42cvQiFSPCp7m4DRtXy1CRzNmRG7FmSK8SgkQOWSWE+6KRKat88j0Nw+Rg6U1YaMBofJOLKfIswLHgW44Bpf2c0eynJEZdLi94oOh7lkTHcaqwBiO1MWg9eiYT/j7qXCPjoi9q3PzPhxoA=
and the decryption result is like this:
result image

How to use bouncycastle opengpg encryptFile,sign and decrypt

At First,please forgive my poor English level。And thanks for your solution!
I am new with bouncycastle。 I have succssed used it creating PGPkeypair ,get PGPPublickKey and secretKey 。I also use secretKey to encrypt a txt file,but I can't signed and decrypt it 。My codes are almost from the org.bouncycastle.openpgp.example and I dont know where the problem is
Here is my codes:
1,Create PGPKeyPair and get PGPPublickey,secretKey and save them:
public static PGPPublicKey generateKeyPair() throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
keyGen.initialize(1024, new SecureRandom());
int algorithm = PGPPublicKey.RSA_GENERAL;
PGPKeyPair pkp=new JcaPGPKeyPair(algorithm, keyGen.generateKeyPair(), new Date());
Security.addProvider(new BouncyCastleProvider());
Security.addProvider(new BouncyCastlePQCProvider());
// 生成RSA密钥对
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
kpg.initialize(4096);
KeyPair kp = kpg.generateKeyPair();
// 转为PGP密钥对
JcaPGPKeyPair pgpKeyPair = new JcaPGPKeyPair(PGPPublicKey.RSA_GENERAL,
kp, new Date());
// 用户标识一般使用email
String identity = "fad#163.com";
// 用来保护密钥的密码
char[] passPhrase = "123456".toCharArray();
PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder()
.build().get(HashAlgorithmTags.SHA1);
PGPContentSignerBuilder certSignerBuilder = new JcaPGPContentSignerBuilder(
pgpKeyPair.getPublicKey().getAlgorithm(),
HashAlgorithmTags.SHA1);
PBESecretKeyEncryptor keyEncryptor = new JcePBESecretKeyEncryptorBuilder(
SymmetricKeyAlgorithmTags.AES_256, sha1Calc,0x90).setProvider("BC").build(
passPhrase);
// 生成PGP密钥
PGPSecretKey secretKey = new PGPSecretKey(
PGPSignature.DEFAULT_CERTIFICATION, pgpKeyPair, identity,
sha1Calc, null, null, certSignerBuilder, keyEncryptor);
// 保存PGP密钥到asc文件
File externalStorageDirectory = Environment
.getExternalStorageDirectory();
String path = externalStorageDirectory.toString();
OutputStream secretOut = new ArmoredOutputStream(new FileOutputStream(
path + "/SecretKey.asc"));
secretKey.encode(secretOut);
secretOut.close();
// 保存PGP公钥到asc文件
OutputStream publicOut = new ArmoredOutputStream(new FileOutputStream(
path + "/PublicKey.asc"));
PGPPublicKey key = secretKey.getPublicKey();
key.encode(publicOut);
publicOut.close();
return key;
}
2,Use SignedFileProcessor.java to encrypt file and decryptfile:
public class KeyBasedLargeFileProcessor{
public static void decryptFile(
String inputFileName,
String keyFileName,
char[] passwd,
String defaultFileName)
throws IOException, NoSuchProviderException
{
InputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
InputStream keyIn = new BufferedInputStream(new FileInputStream(keyFileName));
decryptFile(in, keyIn, passwd, defaultFileName);
keyIn.close();
in.close();
}
/**
* decrypt the passed in message stream
*/
public static void decryptFile(
InputStream in,
InputStream keyIn,
char[] passwd,
String defaultFileName)
throws IOException, NoSuchProviderException
{
in = PGPUtil.getDecoderStream(in);
try
{
PGPObjectFactory pgpF = new PGPObjectFactory(in);
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
//
// the first object might be a PGP marker packet.
//
if (o instanceof PGPEncryptedDataList)
{
enc = (PGPEncryptedDataList)o;
}
else
{
enc = (PGPEncryptedDataList)pgpF.nextObject();
}
//
// find the secret key
//
Iterator it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
PGPUtil.getDecoderStream(keyIn));
while (sKey == null && it.hasNext())
{
pbe = (PGPPublicKeyEncryptedData)it.next();
sKey = PGPExampleUtil.findSecretKey(pgpSec, pbe.getKeyID(), passwd);
}
if (sKey == null)
{
throw new IllegalArgumentException("secret key for message not found.");
}
InputStream clear = pbe.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey));
PGPObjectFactory plainFact = new PGPObjectFactory(clear);
PGPCompressedData cData = (PGPCompressedData)plainFact.nextObject();
InputStream compressedStream = new BufferedInputStream(cData.getDataStream());
PGPObjectFactory pgpFact = new PGPObjectFactory(compressedStream);
Object message = pgpFact.nextObject();
if (message instanceof PGPLiteralData)
{
PGPLiteralData ld = (PGPLiteralData)message;
String outFileName = ld.getFileName();
if (outFileName.length() == 0)
{
outFileName = defaultFileName;
}
InputStream unc = ld.getInputStream();
OutputStream fOut = new BufferedOutputStream(new FileOutputStream(outFileName));
Streams.pipeAll(unc, fOut);
fOut.close();
}
else if (message instanceof PGPOnePassSignatureList)
{
throw new PGPException("encrypted message contains a signed message - not literal data.");
}
else
{
throw new PGPException("message is not a simple encrypted file - type unknown.");
}
if (pbe.isIntegrityProtected())
{
if (!pbe.verify())
{
System.err.println("message failed integrity check");
}
else
{
System.err.println("message integrity check passed");
}
}
else
{
System.err.println("no message integrity check");
}
}
catch (PGPException e)
{
System.err.println(e);
if (e.getUnderlyingException() != null)
{
e.getUnderlyingException().printStackTrace();
}
}
}
public static void encryptFile(
String outputFileName,
String inputFileName,
String encKeyFileName,
boolean armor,
boolean withIntegrityCheck)
throws IOException, NoSuchProviderException, PGPException
{
OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFileName));
PGPPublicKey encKey = PGPExampleUtil.readPublicKey(encKeyFileName);
encryptFile(out, inputFileName, encKey, armor, withIntegrityCheck);
out.close();
}
public static void encryptFile(
OutputStream out,
String fileName,
PGPPublicKey encKey,
boolean armor,
boolean withIntegrityCheck)
throws IOException, NoSuchProviderException
{
if (armor)
{
out = new ArmoredOutputStream(out);
}
try
{
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_256).setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom()).setProvider("BC"));
cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider("BC"));
OutputStream cOut = cPk.open(out, new byte[1 << 16]);
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(
PGPCompressedData.ZIP);
PGPUtil.writeFileToLiteralData(comData.open(cOut), PGPLiteralData.BINARY, new File(fileName), new byte[1 << 16]);
comData.close();
cOut.close();
if (armor)
{
out.close();
}
}
catch (PGPException e)
{
System.err.println(e);
if (e.getUnderlyingException() != null)
{
e.getUnderlyingException().printStackTrace();
}
}
}
}
3,Here are my test code:
private void test() {
File storageDirectory = Environment.getExternalStorageDirectory();
final String opath = storageDirectory.toString();
final File publcKeyFile = new File(storageDirectory, "PublicKey.asc");
if(!publcKeyFile.exists()){
try {
OpenGPGUtil.generateKeyPair();
} catch (Exception e) {
e.printStackTrace();
}
}else {
System.out.println("密钥存在");
}
final File secretKeyFile = new File(storageDirectory, "SecretKey.asc");
final File enFile = new File(storageDirectory, "s.txt");
final File file = new File(storageDirectory, "x.txt");
final File deFile = new File(storageDirectory, "ss.txt");
final String publcKeyfilePath = publcKeyFile.toString();
final String secretKeyFilePath = secretKeyFile.toString();
final String enFilePath = enFile.toString();
final String filePath = file.toString();
final String deFilePath = deFile.toString();
new Thread(new Runnable() {
#Override
public void run() {
try {
KeyBasedLargeFileProcessor.encryptFile(enFilePath,
filePath, publcKeyfilePath, true, true);
// KeyBasedLargeFileProcessor.decryptFile(enFilePath,
// secretKeyFilePath, "123456".toCharArray(),
// deFilePath);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
Here are three line annotation,if I erase them Eclipse's logcat will show:
/System.err(7498): java.io.FileNotFoundException:
/x.txt: open failed: EROFS (Read-only file system)
System.err(7498): at libcore.io.IoBridge.open(IoBridge.java:409)
System.err(7498): at java.io.FileOutputStream
<init(FileOutputStream.java:88)
System.err(7498): at java.io.FileOutputStream
.<init> (FileOutputStream.java:128)
System.err(7498): at java.io.FileOutputStream
.<init>(FileOutputStream.java:117)
System.err(7498): at com.example.opengpgs.KeyBasedLargeFileProcessor.
decryptFile(KeyBasedLargeFileProcessor.java:147)
System.err(7498): at com.example.opengpgs.KeyBasedLargeFileProcessor
.decryptFile(KeyBasedLargeFileProcessor.java:69)
System.err(7498): at com.example.opengpgs.MainActivity$1.
run(MainActivity.java:62)
System.err(7498): at java.lang.Thread.run(Thread.java:841)
System.err(7498): Caused by: libcore.io.ErrnoException:
open failed: EROFS (Read-only file system)
System.err(7498): at libcore.io.Posix.open(Native Method)
System.err(7498): at libcore.io.BlockGuardOs.
open(BlockGuardOs.java:110)
System.err(7498): at libcore.io.IoBridge.open(IoBridge.java:393)
System.err(7498): ... 7 more
IInputConnectionWrapper(7498): getCursorCapsMode on
inactive InputConnection
From the error it seems your filesystem is read-only but you are trying to write in it to the file x.txt

JAVA :- PGP Decrypting using BouncyCastle those encrypted by GPG4win Kleopatra

i am using GPG4Win for encrypt the file and then BouncyCastle for decrypt file but code is not working
suppose i use BouncyCastle code for encrypt file and then use BouncyCastle decryption code its able to decrypt file and GPG4win also able to decrypt the file.
all code in java
suppose file is encrypted by BouncyCastle its decrypt by GPG4win and BouncyCastle
org.bouncycastle.openpgp.PGPException: Exception starting decryption
at org.bouncycastle.openpgp.PGPPublicKeyEncryptedData.getDataStream(Unknown Source)
at org.bouncycastle.openpgp.PGPPublicKeyEncryptedData.getDataStream(Unknown Source)
at org.bouncycastle.openpgp.PGPPublicKeyEncryptedData.getDataStream(Unknown Source)
at com.pgp.util.KeyBasedFileProcessorUtil.decryptFile(KeyBasedFileProcessorUtil.java:183)
at com.pgp.encrypt.PGPDecryption.main(PGPDecryption.java:49)
Caused by: java.security.InvalidKeyException: Illegal key size
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
... 5 more
org.bouncycastle.openpgp.PGPException: Exception starting decryption
java.security.InvalidKeyException: Illegal key size
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at org.bouncycastle.openpgp.PGPPublicKeyEncryptedData.getDataStream(Unknown Source)
at org.bouncycastle.openpgp.PGPPublicKeyEncryptedData.getDataStream(Unknown Source)
at org.bouncycastle.openpgp.PGPPublicKeyEncryptedData.getDataStream(Unknown Source)
at com.pgp.util.KeyBasedFileProcessorUtil.decryptFile(KeyBasedFileProcessorUtil.java:183)
at com.pgp.encrypt.PGPDecryption.main(PGPDecryption.java:49)
my code is
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.PGPEncryptedData;
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;
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.OutputStream;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Iterator;
import java.io.*;
/**
* A simple utility class that encrypts/decrypts public key based
* encryption files.
* <p>
* To encrypt a file: KeyBasedFileProcessor -e [-a|-ai] fileName publicKeyFile.<br>
* If -a is specified the output file will be "ascii-armored".
* If -i is specified the output file will be have integrity checking added.
* <p>
* To decrypt: KeyBasedFileProcessor -d fileName secretKeyFile passPhrase.
* <p>
* Note 1: this example will silently overwrite files, nor does it pay any attention to
* the specification of "_CONSOLE" in the filename. It also expects that a single pass phrase
* will have been used.
* <p>
* Note 2: if an empty file name has been specified in the literal data object contained in the
* encrypted packet a file with the name filename.out will be generated in the current working directory.
*/
public class KeyBasedFileProcessorUtil
{
/**
* A simple routine that opens a key ring file and loads the first available key suitable for
* encryption.
*
* #param in
* #return
* #throws IOException
* #throws PGPException
*/
public static PGPPublicKey readPublicKey(
InputStream in)
throws IOException, PGPException
{
in = PGPUtil.getDecoderStream(in);
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in);
//
// we just loop through the collection till we find a key suitable for encryption, in the real
// world you would probably want to be a bit smarter about this.
//
//
// iterate through the key rings.
//
Iterator rIt = pgpPub.getKeyRings();
while (rIt.hasNext())
{
PGPPublicKeyRing kRing = (PGPPublicKeyRing)rIt.next();
Iterator kIt = kRing.getPublicKeys();
while (kIt.hasNext())
{
PGPPublicKey k = (PGPPublicKey)kIt.next();
if (k.isEncryptionKey())
{
return k;
}
}
}
throw new IllegalArgumentException("Can't find encryption key in key ring.");
}
/**
* Search a secret key ring collection for a secret key corresponding to
* keyID if it exists.
*
* #param pgpSec a secret key ring collection.
* #param keyID keyID we want.
* #param pass passphrase to decrypt secret key with.
* #return
* #throws PGPException
* #throws NoSuchProviderException
*/
public static PGPPrivateKey findSecretKey(
PGPSecretKeyRingCollection pgpSec,
long keyID,
char[] pass)
throws PGPException, NoSuchProviderException
{
PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
if (pgpSecKey == null)
{
return null;
}
return pgpSecKey.extractPrivateKey(pass, "BC");
}
/**
* decrypt the passed in message stream
*/
public static void decryptFile(
InputStream in,
InputStream keyIn,
char[] passwd,
String defaultFileName)
throws Exception
{
System.out.println("File Decrypting");
System.out.println("File absulatePath :-");
in = PGPUtil.getDecoderStream(in);
try
{
PGPObjectFactory pgpF = new PGPObjectFactory(in);
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
//
// the first object might be a PGP marker packet.
//
if (o instanceof PGPEncryptedDataList)
{
enc = (PGPEncryptedDataList)o;
}
else
{
enc = (PGPEncryptedDataList)pgpF.nextObject();
}
//
// find the secret key
//
System.out.println("find the secret key");
Iterator it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
PGPUtil.getDecoderStream(keyIn));
while (sKey == null && it.hasNext())
{
pbe = (PGPPublicKeyEncryptedData)it.next();
sKey = findSecretKey(pgpSec, pbe.getKeyID(), passwd);
}
if (sKey == null)
{
System.out.println("--------------------");
System.out.println("secret key for message not found.");
throw new IllegalArgumentException("secret key for message not found.");
}
System.out.println("secret key for message found.");
InputStream clear = pbe.getDataStream(sKey, "BC");
PGPObjectFactory plainFact = new PGPObjectFactory(clear);
Object message = plainFact.nextObject();
if (message instanceof PGPCompressedData)
{
PGPCompressedData cData = (PGPCompressedData)message;
PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream());
message = pgpFact.nextObject();
}
if (message instanceof PGPLiteralData)
{
PGPLiteralData ld = (PGPLiteralData)message;
String outFileName = ld.getFileName();
if (ld.getFileName().length() == 0)
{
outFileName = defaultFileName;
}
InputStream unc = ld.getInputStream();
int ch;
while ((ch = unc.read()) >= 0)
{
fOut.write(ch);
}
}
else if (message instanceof PGPOnePassSignatureList)
{
System.out.println("encrypted message contains a signed message - not literal data.");
throw new PGPException("encrypted message contains a signed message - not literal data.");
}
else
{
throw new PGPException("message is not a simple encrypted file - type unknown.");
}
if (pbe.isIntegrityProtected())
{
if (!pbe.verify())
{
System.err.println("message failed integrity check");
}
else
{
System.err.println("message integrity check passed");
}
}
else
{
System.err.println("no message integrity check");
}
}
catch (PGPException e)
{
e.printStackTrace();
System.err.println(e);
if (e.getUnderlyingException() != null)
{
e.getUnderlyingException().printStackTrace();
}
}
}
/*
private static void decryptFile(
InputStream in,
InputStream keyIn,
char[] passwd)
throws Exception
{
in = PGPUtil.getDecoderStream(in);
try
{
PGPObjectFactory pgpF = new PGPObjectFactory(in);
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
//
// the first object might be a PGP marker packet.
//
if (o instanceof PGPEncryptedDataList)
{
enc = (PGPEncryptedDataList)o;
}
else
{
enc = (PGPEncryptedDataList)pgpF.nextObject();
}
//
// find the secret key
//
Iterator it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
while (sKey == null && it.hasNext())
{
pbe = (PGPPublicKeyEncryptedData)it.next();
sKey = findSecretKey(keyIn, pbe.getKeyID(), passwd);
}
if (sKey == null)
{
throw new IllegalArgumentException("secret key for message not found.");
}
InputStream clear = pbe.getDataStream(sKey, "BC");
PGPObjectFactory plainFact = new PGPObjectFactory(clear);
PGPCompressedData cData = (PGPCompressedData)plainFact.nextObject();
InputStream compressedStream = new BufferedInputStream(cData.getDataStream());
PGPObjectFactory pgpFact = new PGPObjectFactory(compressedStream);
Object message = pgpFact.nextObject();
if (message instanceof PGPLiteralData)
{
PGPLiteralData ld = (PGPLiteralData)message;
FileOutputStream fOut = new FileOutputStream(ld.getFileName());
BufferedOutputStream bOut = new BufferedOutputStream(fOut);
InputStream unc = ld.getInputStream();
int ch;
while ((ch = unc.read()) >= 0)
{
bOut.write(ch);
}
bOut.close();
}
else if (message instanceof PGPOnePassSignatureList)
{
throw new PGPException("encrypted message contains a signed message - not literal data.");
}
else
{
throw new PGPException("message is not a simple encrypted file - type unknown.");
}
if (pbe.isIntegrityProtected())
{
if (!pbe.verify())
{
System.err.println("message failed integrity check");
}
else
{
System.err.println("message integrity check passed");
}
}
else
{
System.err.println("no message integrity check");
}
}
catch (PGPException e)
{
System.err.println(e);
if (e.getUnderlyingException() != null)
{
e.getUnderlyingException().printStackTrace();
}
}
}
*/
public static void encryptFile(
OutputStream out,
String fileName,
PGPPublicKey encKey,
boolean armor,
boolean withIntegrityCheck)
throws IOException, NoSuchProviderException
{
if (armor)
{
out = new ArmoredOutputStream(out);
}
try
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(1);
PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
comData.close();
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, withIntegrityCheck, new SecureRandom(), "BC");
cPk.addMethod(encKey);
byte[] bytes = bOut.toByteArray();
OutputStream cOut = cPk.open(out, bytes.length);
cOut.write(bytes);
cOut.close();
out.close();
}
catch (PGPException e)
{
System.err.println(e);
if (e.getUnderlyingException() != null)
{
e.getUnderlyingException().printStackTrace();
}
}
}
public static void encryptFile1(
OutputStream out,
String fileName,
PGPPrivateKey encKey,
boolean armor,
boolean withIntegrityCheck)
throws IOException, NoSuchProviderException
{
if (armor)
{
out = new ArmoredOutputStream(out);
}
try
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(1);
PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
comData.close();
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, withIntegrityCheck, new SecureRandom(), "BC");
cPk.addMethod((PGPPublicKey) encKey.getKey());
byte[] bytes = bOut.toByteArray();
OutputStream cOut = cPk.open(out, bytes.length);
cOut.write(bytes);
cOut.close();
out.close();
}
catch (PGPException e)
{
System.err.println(e);
if (e.getUnderlyingException() != null)
{
e.getUnderlyingException().printStackTrace();
}
}
}
}
Decryption classs
public class PGPDecryption {
/**
*
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Properties prop=new Properties();
try {
prop.load(new FileInputStream("config.prop"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream keyOut=null;
FileOutputStream out =null;
Security.addProvider(new BouncyCastleProvider());
try {
System.out.println(prop.getProperty(Constant.PRIVATE_KEY));
keyOut = new FileInputStream(prop.getProperty(Constant.PRIVATE_KEY));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
KeyBasedFileProcessorUtil.decryptFile(new FileInputStream(prop.getProperty(Constant.ENCRYPT_FILE_PATH)), keyOut, prop.getProperty(Constant.PRIVATE_FILE_PASS).toCharArray(), prop.getProperty(Constant.DECRYPT_FILE_OUTPUT_PATH));
System.out.println("Decrypted File created with name of "+prop.getProperty(Constant.DECRYPT_FILE_OUTPUT_PATH));
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Encryption class
public class PGPEncryption {
public static void main(String[] args) {
// TODO Auto-generated method stub
Properties prop=new Properties();
try {
File f=new File("config.prop");
System.out.println(f.getAbsolutePath());
prop.load(new FileInputStream(f));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream keyIn=null;
FileOutputStream out =null;
Security.addProvider(new BouncyCastleProvider());
try {
System.out.println(prop.getProperty(Constant.PUBLIC_KEY));
keyIn = new FileInputStream(prop.getProperty(Constant.PUBLIC_KEY));
System.out.println("Encrypt File Path :-"+prop.getProperty(Constant.ENCRYPT_FILE_PATH));
out= new FileOutputStream(new File(prop.getProperty(Constant.ENCRYPT_FILE_PATH)));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean armor = false;
boolean integrityCheck = false;
PGPPublicKey pubKey = null;
try {
System.out.println("Reading public key.........");
pubKey = KeyBasedFileProcessorUtil.readPublicKey(keyIn);
System.out.println("Public Key found...........");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PGPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println("File Encrypting............");
KeyBasedFileProcessorUtil.encryptFile(out, prop.getProperty(Constant.SOURCE_FILE_PATH), pubKey, armor, integrityCheck);
System.out.println("Encrypted File created with name of "+prop.getProperty(Constant.ENCRYPT_FILE_PATH));
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
please help me i want to decrypt the file those encrypted by GPG4win
To solve this problem now, i am using Cryptix OpenPGP.
its working properly without any error or exception.
link to download Cryptix lib
http://www.cryptix.org/
in that download two project library
Cryptix OpenPGP
Cryptix JCE

Getting damaged file error after downloading a pdf

I followed this example to let the user download the pdf :
Vaadin Example
/** Copied from example */
#Override
protected void init(VaadinRequest request) {
Button downloadButton = new Button("Download image");
StreamResource myResource = createResource();
FileDownloader fileDownloader = new FileDownloader(myResource);
fileDownloader.extend(downloadButton);
setContent(downloadButton);
}
/** modified from example */
private StreamResource createResource() throws IOException {
return new StreamResource(new StreamSource() {
byte[] bytes =loadFile("/home/amira/Desktop/repTest.pdf"); //Get the file bytes here
InputStream is = new ByteArrayInputStream(bytes);
#Override
public InputStream getStream() {
return is ;
}
}, "report.pdf");
}
public static byte[] readFully(InputStream stream) throws IOException {
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = stream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
}
public static byte[] loadFile(String sourcePath) throws IOException {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(sourcePath);
return readFully(inputStream);
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
When I try to open the file , it says damaged file
See my working sample (tested for 20Mb PDFs):
private void downloadDocument()
{
final String retrievalName = "222.pdf";
class FileDownloadResource extends FileResource
{
public FileDownloadResource(File sourceFile, Application application)
{
super(sourceFile, application);
}
public DownloadStream getStream()
{
try
{
byte[] DocContent = null;
DocContent = getFileBytes("C:\\Temp\\222.pdf");
if (DocContent != null)
{
final DownloadStream ds = new DownloadStream(new ByteArrayInputStream(DocContent), "application/pdf", retrievalName);
ds.setCacheTime(getCacheTime());
String fileName = URLEncoder.encode(retrievalName, "UTF8");
// force download!
ds.setParameter("Content-Disposition", "attachment; filename*=\"utf-8'" + fileName + "\"");
return ds;
}
else
{
return null;
}
}
catch (Exception e1)
{
e1.printStackTrace();
return null;
}
}
}
getApplication().getMainWindow().open(new FileDownloadResource(new File(retrievalName), getApplication()));
}
/**
* getFileBytes
*
* #author NBochkarev
*
* #param fileOut
* #return
* #throws IOException
*/
public static byte[] getFileBytes(String fileName) throws IOException
{
ByteArrayOutputStream ous = null;
InputStream ios = null;
try
{
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = new FileInputStream(new File(fileName));
int read = 0;
while ((read = ios.read(buffer)) != -1)
ous.write(buffer, 0, read);
}
finally
{
try
{
if (ous != null)
ous.close();
}
catch (IOException e)
{
// swallow, since not that important
}
try
{
if (ios != null)
ios.close();
}
catch (IOException e)
{
// swallow, since not that important
}
}
return ous.toByteArray();
}

Categories