我有很多非常小的数据(19字节)需要加密并以加密格式通过TCP发送到远程服务器。 我正在使用以下代码执行此操作。
package aesclient;
import java.io.OutputStream;
import java.net.Socket;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESClient {
static byte[] plaintext = new byte[] {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53};
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 1337); // connecting to server on localhost
OutputStream outputStream = socket.getOutputStream();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
String s_key = "Random09" + "Random09"; // 16 Byte = 128 Bit Key
byte[] b_key = s_key.getBytes();
SecretKeySpec sKeySpec = new SecretKeySpec(b_key, "AES");
SecureRandom random = SecureRandom.getInstanceStrong();
byte[] IV = new byte[16]; // initialization vector
int num = 10000;
long start = System.nanoTime();
for (int i = 0; i < num; ++i) {
random.nextBytes(IV);
IvParameterSpec ivSpec = new IvParameterSpec(IV);
cipher.init(Cipher.ENCRYPT_MODE, sKeySpec, ivSpec);
byte[] msg = new byte[16 + 32];
System.arraycopy(IV, 0, msg, 0, IV.length);
byte[] encrypted = cipher.doFinal(plaintext);
System.arraycopy(encrypted, 0, msg, IV.length, encrypted.length);
outputStream.write(msg);
outputStream.flush();
}
long end = System.nanoTime();
long duration = end - start;
double drate = ((double)plaintext.length*(double)num)/((double)duration/1000000000);
System.out.println("Verschlüsselung:\n" + num + " mal 19 Bytes in " + ((double)duration/1000000000) + " s\nData Rate = " + drate/1000.0 + " kBytes/s");
}
catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
我想知道为什么它运行得非常缓慢。我得到了这样的输出:
Verschlüsselung:
10000 mal 19 Bytes in 2.566016627 s
Data Rate = 74.04472675694785 kBytes/s
这意味着我在发送原始(未加密)数据的情况下,拥有每秒74千字节的数据传输速率。如果我不通过TCP发送数据,这个速率只会略微增加(大约100千字节/秒)。根据我的阅读,有一些数据传输速率可达到20兆字节/秒甚至更高。我的电脑运行Windows 10操作系统,搭载i5处理器。非常感谢任何帮助。正如我所说,我只需要传输许多小的加密数据包(19字节)。