在 java 中进行加密的正确方法

Right way to do encryption in java

我对加密的东西完全陌生,我对 java 中的加密有一些疑问 我曾经在 java

中对 RSA 加密执行此操作
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPTION_MODE,publicKey);
byte result = cipher.doFinal(data);

使用 AES 的方式相同,我使用此代码生成 AES 密钥

SecureRandom random = new SecureRandom();
byte [] key = new byte [16];
random.nextByte(key);
SecretKeySpec secretKey = new SecretKeySpec(key,"AES");

但是正如我在其他程序代码中看到的那样,这不是他们使用加密的方式我总是看到他们在 AES 中使用一些东西作为 IV 参数并且他们从不使用 "AES" 或 "RSA" 来获得密码实例。 我用来加密数据的方式安全吗? 我确定我遗漏了什么

更新:

我还有一个关于在 AES 加密中更改数据大小的问题,就像我使用 AES 加密数据一样,它将数据大小从 1024 更改为 1040

    byte key [] = new byte[16];
    SecureRandom random = new SecureRandom();
    random.nextBytes(key);
    SecretKeySpec keySpec = new SecretKeySpec(key,"AES");
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.ENCRYPT_MODE,keySpec);
    FileInputStream in = new FileInputStream("test.txt");
    byte [] buffer = new byte[1024];
    byte [] encrypted;
    while (in.read()>0){
        encrypted = c.doFinal(buffer);
        System.out.println(encrypted.length);
    }

输出是: 1040 1040 . . 1040

简单加密的数据大小总是比原始数据多16字节 我必须处理这个还是因为我使用 Cipher.getInstance("AES");

这不是推荐的方式,您需要更改它。您可能希望更好地了解 Whosebug。您的问题在 post How to encrypt String in Java.

中得到(直接)回答

确保您进一步查看所有答案。比如this one will probably help you to understand更多。