【发布时间】:2015-02-07 12:32:53
【问题描述】:
我正在尝试实现 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
【问题讨论】:
-
我不得不问你为什么要编写自己的加密代码。如果不是用于图像解密只是尝试编写加密的借口的玩具项目,我强烈建议使用(更安全的)预先编写的实现。
-
我必须通过我的实现来测试它。
-
呃,到底测试什么?
-
此外,逐字节加密是不安全的(它等同于替换密码,它对已知明文攻击非常失败,而对选择明文攻击完全失败)
-
1) 使用混合加密 2) 教科书 RSA 完全损坏。
标签: java encryption cryptography rsa