我看到 JCPABE项目,但类中的方法使我能够加密文件或 InputStream,但不能加密简单的 Java 字符串。如何使用这些方法来加密/解密字符串?我尝试将字符串转换为字节数组,但它不起作用(即 String.getBytes("UTF_8");
如果我将 String
转换为 InputStream
。如何加密/解密一个简单的字符串?
示例: 我的简单代码:
String test="Message";
policy="newyork or losangeles";
Cpabe.encrypt(publickey, policy, test, test);
我收到此消息:Cpabe 类型中的方法 encrypt(File, String, File, File) 不适用于参数 (File, String, String, String)。
加密函数是这样的:
public static void encrypt(File publicKeyFile, String policy, File inputFile, File outputFile) throws IOException, AbeEncryptionException {
AbePublicKey publicKey = AbePublicKey.readFromFile(publicKeyFile);
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(inputFile));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile))) {
encrypt(publicKey, policy, in, out);
}
我已经更改了以下功能:
public static void encrypt(File publicKeyFile, String policy, String inputstr, String outputstr) throws IOException, AbeEncryptionException {
AbePublicKey publicKey = AbePublicKey.readFromFile(publicKeyFile);
try (String in = new String(inputstr);
String out = new String(outputstr)) {
encrypt(publicKey, policy, in, out);
}
}
但我还有其他消息:资源类型 String 没有在 String in 和 String out 上实现 java.lang.AutoCloseable ;在加密时,我收到以下消息: Cpabe 类型中的方法 encrypt(AbePublicKey, String, InputStream, OutputStream) 不适用于参数 (AbePublicKey, String, String, String)。
这是带有 2 个 InputStream 参数的函数:
public static void encrypt(AbePublicKey publicKey, String policy, InputStream input, OutputStream output) throws AbeEncryptionException, IOException {
AbeEncrypted encrypted = encrypt(publicKey, policy, input);
encrypted.writeEncryptedData(output, publicKey);
}
这是 writeEncryptedData 方法:
public void writeEncryptedData(OutputStream out, AbePublicKey publicKey) throws IOException {
AbeOutputStream abeOut = new AbeOutputStream(out, publicKey);
Version.writeToStream(abeOut);
cipher.writeToStream(abeOut);
abeOut.writeInt(iv.length);
abeOut.write(iv);
byte[] buffer = new byte[1024];
int len;
while ((len = dataStream.read(buffer)) != -1) {
abeOut.write(buffer, 0, len);
}
}
最佳答案
你的代码由于各种原因不能。首先,您需要一个输入流和输出流。要使用字符串,您必须首先将其转换为 byte[]
然后到一个流。
在你的函数中,你定义了类似“输出参数”的东西 String outputstr
。然而,字符串在 Java 中是不可变的,因此您不能以这种方式使用它并更改它的内容。使用它作为返回值。
第三,永远不要尝试转换byte[]
至String
使用new String(<byte array>)
。这不会返回具有可打印字符的字符串,而是返回具有二进制不可打印内容的字符串。你必须对其进行编码,例如使用base64。在解密之前,您必须应用 Base64 解码。
public static String encrypt(File publicKeyFile, String policy, String inputstr) throws IOException, AbeEncryptionException {
AbePublicKey publicKey = AbePublicKey.readFromFile(publicKeyFile);
try (InputStream in = new ByteArrayInputStream(inputstr.getBytes(StandardCharsets.UTF_8);
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
encrypt(publicKey, policy, in, out);
return Base64.getEncoder().encodeToString(out.toByteArray());
}
}
关于java - JCPABE 加密解密字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39851317/