无法使用 RSA 加密图像

can't encrypt image withe RSA

我正在尝试使用 java 中的 RSA 加密 BMP 图像,它应该创建加密和解密的图像。

好的,所以在阅读评论后了解到单独使用 RSA 是不安全的;我编辑了我的问题。并尝试 Java 密码学,但 cipher.doFinal() 不接受超过 245 字节的数据

    File bmpFile = new File("C:\Users\acer\Desktop\py\6.bmp");
    BufferedImage image = ImageIO.read(bmpFile);
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    ImageIO.write(image, "bmp", baos );
    byte[] b = baos.toByteArray();
    byte[] b1=new byte[b.length];   

    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    keyPairGen.initialize(2048);
    KeyPair pair = keyPairGen.generateKeyPair();
    PublicKey publicKey = pair.getPublic();
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    cipher.update(b);
    b1 = cipher.doFinal();
    bmpFile=new File("C:\Users\acer\Desktop\py\66.bmp");
    FileOutputStream fos = new FileOutputStream(bmpFile);
    fos.write(b1);
    fos.flush();
    fos.close();

它给出:

Exception in thread "main" javax.crypto.IllegalBlockSizeException: Data must not be longer than 245 bytes
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:344)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
at javax.crypto.Cipher.doFinal(Cipher.java:2048)

我的大部分图片都是 198x135 我在堆栈 onverflow 中发现

The RSA algorithm can only encrypt data that has a maximum byte length of the RSA key length in bits divided with eight minus eleven padding bytes, i.e. number of maximum bytes = key length in bits / 8 - 11.

并说你必须用对称密钥加密数据并用rsa加密对称密钥。 但我想用 RSA 加密数据。

And i went to ask,i have to send the encrypting image to Other pc but the problem is that p,q are random

非对称加密意味着针对特定目标(public 密钥)进行加密。

所以步骤是:

  • 接收方创建其私钥(p、q、e)和public密钥(N、d)私钥(p、q、d)和public 键 (N, e)
  • 接收方将其 public 密钥发送给发送方
  • 发件人使用 public 密钥加密消息
  • 接收方可以使用其私钥解密数据

因此,如果您想使用 RSA 加密任何数据,参数对于目标接收方是随机的,但对于发送方是给定的。

do i have to encrypt theme with Symmetric algorithm like RC4 and send theme with the image

您可能已经发现,RSA 操作非常慢。因此,使用 RSA 的常见方法是 混合加密 - 使用随机对称加密密钥加密数据并使用 RSA 仅加密随机密钥。

image.setRGB(i, j,pixels[i][j].intValue());

这行不通。任何数据的加密都将具有密钥长度。实际上,您的情况下每个图像像素都需要 1024 位。将 bigint 修剪为 intValue 您正在丢失信息。

这就是使用(已经提到的)混合加密的原因

it's part of my School Project

如果您将 RSA 用于实际项目:

  • 教科书RSA有几个弱点,为了解决方案安全,需要使用padding,常用标准是pkcs#1 v1.5或OAEP padding
  • 实际上你应该使用默认的加密库,它更快并且可以抵御边信道攻击