简体   繁体   English

使用RSA(Java)加密长字符串

[英]Encrypt long String with RSA (Java)

I'm having problems with an RSA application I have to do in Java. 我在使用Java时遇到的RSA应用程序出现问题。

I have to read a string from a file, encrypt it, and then save the encrypted string in a new file. 我必须从文件中读取一个字符串,对其进行加密,然后将加密的字符串保存在一个新文件中。

My RSA key is 1024 bits long. 我的RSA密钥长度为1024位。

The code's part where the problem is, is the following: 问题所在的代码部分如下:

            readBytes = in.read(bytesToBeEncoded, 0, bytesToBeEncoded.length);

            while(readBytes != -1){
                encodedContent = ciph.update(bytesToBeEncoded, 0, readBytes);
                out.write(encodedContent);
                bytesToBeEncoded= new byte[(KEY_SIZE/8)-11];
                readBytes = in.read(bytesToBeEncoded, 0, bytesToBeEncoded.length);                  
            }

            encodedContent = ciph.doFinal();
            out.write(encodedContent);

Where the variables are defined like this: 变量定义如下:

        byte[] bytesToBeEncoded = new byte[(KEY_SIZE/8)-11]; 

        FileInputStream in = new FileInputStream(new File(file1));
        FileOutputStream out = new FileOutputStream(new File(file2));
        int readBytes;

The point is that when I encrypt a less-than-117 bytes string, it works perfectly (encrypt and then decrypt well), but when the size is larger, the application throws this exception: 关键是当我加密一个小于117字节的字符串时,它完美地工作(加密然后解密),但是当大小更大时,应用程序抛出此异常:

javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes

Thrown by: 抛出:

encodedContent = ciph.doFinal();

I don't know where the problem is and what I have to do. 我不知道问题出在哪里以及我必须做什么。

Could anyone help me? 谁能帮助我? Thank you. 谢谢。

Sorry about my english. 抱歉我的英语。

The problem is with how you are initializing the byte array that you are reading your input. 问题在于如何初始化正在读取输入的字节数组。 You are setting the size based on the size of the RSA key instead of by the expected size of your input stream. 您正在根据RSA密钥的大小而不是输入流的预期大小来设置大小。

byte[] bytesToBeEncoded = new byte[(KEY_SIZE/8)-11];

The key size is 1024 bits, so 1024/8 -11 = 128 - 11 = 117 bytes. 密钥大小为1024位,因此1024/8 -11 = 128 - 11 = 117字节。 This is the amount of data that you can read from the stream, and should not be related to the size of your RSA key. 这是您可以从流中读取的数据量,而不应与RSA密钥的大小相关。

You should initialize the byte array to be the maximum size of data that you'll need to read in, which will avoid the Exception. 您应该将字节数组初始化为您需要读入的最大数据大小,这将避免异常。 For example: 例如:

byte[] bytesToBeEncoded = 1024;

would allow a maximum input string of 1024 characters. 允许最大输入字符串为1024个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM