[英]File Encryption Using RSA
我正在尝试实现RSA算法。 我想加密图像。 问题是解密完成后,无法读取文件。 我不知道问题出在哪里。 这是RSA的实现:
import java.awt.image.BufferedImage;
import java.math.BigInteger;
import java.util.Random;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class RSA {
private BigInteger p;
private BigInteger q;
private BigInteger N;
private BigInteger phi;
private BigInteger e;
private BigInteger d;
private int bitlength = 1024;
private Random r;
public RSA() {
r = new Random();
p = BigInteger.probablePrime(bitlength, r);
q = BigInteger.probablePrime(bitlength, r);
N = p.multiply(q);
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitlength/2, r);
System.out.println("e : "+e);
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0 ) {
e.add(BigInteger.ONE);
}
d = e.modInverse(phi);
}
这是主要方法:
public static void main (String[] args) throws IOException
{
RSA rsa = new RSA();
byte[] bytesImage= rsa.readBytesFromFile(new File(
"F:\\calla.jpg"));
//readBytesFromFile: method to read file as bytes
byte[] encrypted = rsa.encrypt(bytesImage);
writeBytesToFile(new File(
"F:\\encryptedcalla.jpg"),encrypted );
//writeBytesToFile: method to write as bytes
// decrypt
byte[] decrypted = rsa.decrypt(encrypted);
writeBytesToFile(new File(
"F:\\decryptedcalla.jpg"),decrypted );
}
这是加密方法:
// Encrypt image
public byte[] encrypt(byte[] image) {
byte[] encryptedImage = new byte[image.length];
for (int i =0 ; i< image.length; i++){
encryptedImage[i]= (BigInteger.valueOf(image[i])).modPow(e, N).byteValue();
}
return encryptedImage;
}
这是解密方法:
public byte[] decrypt(byte[] image) {
byte[] decryptedImage = new byte[image.length];
for (int i =0 ; i< image.length; i++){
decryptedImage[i]= (BigInteger.valueOf(image[i])).modPow(d, N).byteValue();
}
return decryptedImage;
}
此处描述了读写方法: http : //www.java2s.com/Code/Java/File-Input-Output/Readfiletobytearrayandsavebytearraytofile.htm
正如您所说,问题在于此步骤:
encryptedImage[i]= (BigInteger.valueOf(image[i])).modPow(e, N).byteValue();
问题是, modPow()
返回的是1024位数字,而您试图将其填充到8位字节中。 您不能在不丢失某些信息的情况下执行此操作,如果丢失任何信息,则将无法解密该消息。
RSA是一种数学密码术:您必须将消息编码为数字,然后通过计算将该数字转换为其他数字的函数(即modPow(e, N)
)进行加密。 然后,您必须传输整个加密的消息号。
邮件的接收者获取加密的号码,并通过解密函数modPow(d, N)
运行该号码,该函数应返回原始号码,然后可以将其转换回原始邮件。
但是接收者必须获得整个1024位数字才能使解密工作。
如果使用RSA加密图像的每个字节,则对于加密算法中的每个字节,您都必须向接收者发送一个1024位的数据包。 然后,接收者可以解密该数据包,并提取原始字节。
或者,您可以一次加密两个字节,或者十个字节,或者一百个字节; 但是您不能做的是使“数据包”小于1024位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.