[英]PGP Encryption of Java String
我需要使用 PGP 加密來加密 java 字符串(它是 JSON 文件的一部分)。 我嘗試了很多可以從 Google 搜索中挖掘出的示例。 所有這些示例都使用了 bouncycastle openpgp 方法,這些方法已被棄用。 下面是我使用的代碼:
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
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 org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPUtil;
public class BouncyCastlePGPTest {
public static void main(String[] args) {
// the keyring that holds the public key we're encrypting with
String publicKeyFilePath = "C:\\pgp6.5.8\\pubring.pkr";
// init the security provider
Security.addProvider(new BouncyCastleProvider());
try {
System.out.println("Creating a temp file...");
// create a file and write the string to it
File outputfile = File.createTempFile("pgp", null);
FileWriter writer = new FileWriter(outputfile);
writer.write("the message I want to encrypt".toCharArray());
writer.close();
System.out.println("Temp file created at ");
System.out.println(outputfile.getAbsolutePath());
System.out.println("Reading the temp file to make sure that the bits were written\n----------------------------");
BufferedReader isr = new BufferedReader(new FileReader(outputfile));
String line = "";
while ((line = isr.readLine()) != null) {
System.out.println(line + "\n");
}
// read the key
FileInputStream in = new FileInputStream(publicKeyFilePath);
PGPPublicKey key = readPublicKey(in);
// find out a little about the keys in the public key ring
System.out.println("Key Strength = " + key.getBitStrength());
System.out.println("Algorithm = " + key.getAlgorithm());
int count = 0;
for (java.util.Iterator iterator = key.getUserIDs(); iterator.hasNext();) {
count++;
System.out.println((String)iterator.next());
}
System.out.println("Key Count = " + count);
// create an armored ascii file
FileOutputStream out = new FileOutputStream(outputfile.getAbsolutePath() + ".asc");
// encrypt the file
encryptFile(outputfile.getAbsolutePath(), out, key);
System.out.println("Reading the encrypted file\n----------------------------");
BufferedReader isr2 = new BufferedReader(new FileReader(new File(outputfile.getAbsolutePath() + ".asc")));
String line2 = "";
while ((line2 = isr2.readLine()) != null) {
System.out.println(line2);
}
} catch (PGPException e) {
System.out.println(e.toString());
System.out.println(e.getUnderlyingException().toString());
} catch (Exception e) {
System.out.println(e.toString());
}
}
private static PGPPublicKey readPublicKey(InputStream in) throws IOException {
try {
PGPPublicKeyRing pgpPub = new PGPPublicKeyRing(in);
return pgpPub.getPublicKey();
} catch (IOException io) {
System.out.println("readPublicKey() threw an IOException");
System.out.println(io.toString());
throw io;
}
}
private static void encryptFile(String fileName, OutputStream out, PGPPublicKey encKey)
throws IOException, NoSuchProviderException, PGPException
{
out = new ArmoredOutputStream(out);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
System.out.println("creating comData...");
// get the data from the original file
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
comData.close();
System.out.println("comData created...");
System.out.println("using PGPEncryptedDataGenerator...");
// object that encrypts the data
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(PGPEncryptedDataGenerator.CAST5, new SecureRandom(), "BC");
cPk.addMethod(encKey);
System.out.println("used PGPEncryptedDataGenerator...");
// take the outputstream of the original file and turn it into a byte array
byte[] bytes = bOut.toByteArray();
System.out.println("wrote bOut to byte array...");
// write the plain text bytes to the armored outputstream
OutputStream cOut = cPk.open(out, bytes.length);
cOut.write(bytes);
// cOut.close();
cPk.close();
out.close();
}
}
以下是我的錯誤日志的快照:
BouncyCastlePGPTest.java:96: cannot find symbol
symbol : constructor PGPPublicKeyRing(java.io.InputStream)
location: class org.bouncycastle.openpgp.PGPPublicKeyRing
PGPPublicKeyRing pgpPub = new PGPPublicKeyRing(in);
BouncyCastlePGPTest.java:126: cannot find symbol
symbol : constructor PGPEncryptedDataGenerator(int,java.security.SecureRandom,java.lang.String)
location: class org.bouncycastle.openpgp.PGPEncryptedDataGenerator
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(PGPEncryptedDataGenerator.CAST5, new SecureRandom(), "BC");
^
BouncyCastlePGPTest.java:127: addMethod(org.bouncycastle.openpgp.operator.PGP
KeyEncryptionMethodGenerator) in org.bouncycastle.openpgp.PGPEncryptedDataGen
erator cannot be applied to (org.bouncycastle.openpgp.PGPPublicKey)
cPk.addMethod(encKey);
^
有人可以指出我可以與來自https://www.bouncycastle.org/latest_releases.html的最新 jars 一起使用的工作示例代碼嗎?
除了bouncycastle,還有其他選擇嗎? 我相信這是人們會遇到的一個非常常見的用例。 這些天正在使用什么,如果不是 bouncycastle openpgp?
Bouncy Castle是Java輕量級加密API和Java安全提供程序。 它還為特定功能提供了單獨的庫,主要是CMS(加密消息語法)和PGP(很好的隱私)。
這些庫可以單獨下載,也可以在完整的加密發行版中下載。 它們分別被命名為bcpkix-jdk15on-159.jar
和bcpg-jdk15on-159.jar
(對於1.59版)。 您需要在類路徑或Maven設置中包括這些庫以執行編譯。
如果您的項目不使用擴展的API,而是通過標准Java API訪問所有內容,則實際上可以在編譯過程中 bcprov-...
Bouncy Castle 提供程序 bcprov-...
但是,您只能通過Bouncy Castle本身的PGP API使用PGP功能,因此不適用於PGP。
由於api更改,我與您有相同的例外。 至此,完成了示例代碼。
private static PGPPublicKey readPublicKey(InputStream in) throws IOException {
try {
PGPPublicKeyRing pgpPub = new PGPPublicKeyRing(in, new JcaKeyFingerprintCalculator());
//PGPPublicKeyRing pgpPub = new PGPPublicKeyRing(in);
return pgpPub.getPublicKey();
} catch (IOException io) {
System.out.println("readPublicKey() threw an IOException");
System.out.println(io.toString());
throw io;
}
}
private static void encryptFile(String fileName, OutputStream out, PGPPublicKey encKey)
throws IOException, NoSuchProviderException, PGPException
{
out = new ArmoredOutputStream(out);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
System.out.println("creating comData...");
// get the data from the original file
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
comData.close();
System.out.println("comData created...");
System.out.println("using PGPEncryptedDataGenerator...");
// object that encrypts the data
//PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(PGPEncryptedDataGenerator.CAST5, new SecureRandom(), "BC");
//cPk.addMethod(encKey);
// object that encrypts the data
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5)
.setSecureRandom(new SecureRandom()).setProvider("BC"));
cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encKey));
System.out.println("used PGPEncryptedDataGenerator...");
// take the outputstream of the original file and turn it into a byte array
byte[] bytes = bOut.toByteArray();
System.out.println("wrote bOut to byte array...");
// write the plain text bytes to the armored outputstream
OutputStream cOut = cPk.open(out, bytes.length);
cOut.write(bytes);
// cOut.close();
cPk.close();
out.close();
}
要說一下字符串加密,這取決於您的要求。 您知道甚至base64編碼也可能是一種選擇。
您可以在Google上搜索或搜索該站點,找到了很多。
編碼好
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.