使用 AES 加密文件,使用共享密码

encrypt files with AES , with shared password

我想用 AES 加密/解密,共享 密码,我的代码与 .

相同

链接代码工作正常,但其中没有共享密码。

如何为以下实现添加共享密码?

我需要类似的东西

String shared="xxx..";//some password with 16 digits length

可能吗?

并将此共享密码添加到加密中。

非常重要的一点是,用于 AES 加密的密钥不容易被猜到,因此在很多实现中,密钥都是随机生成的。密钥本身是 16(128 位)、24(192 位)或 32(256 位)字节长度的字节数组,字节数组不能用作共享密码的来源。

解决方案是将字节数组编码为 Base64 编码的字符串,然后以安全的方式将此字符串传递给接收方。接收方将字符串解码回字节数组,并进一步通过 SecretKeySpec 解码为密钥。

这个小例子展示了安全地生成不同长度的随机密码的方法(这个例子只使用了 128 位的密钥长度,对其进行编码并解码回一个秘密密钥——原始的 SecretKey k 与重新生成的相比SecretKex kReceived.

只是最后通知,但它是一个 安全警告:您的加密方法使用的是不安全的 AES ECB 模式 - 请不要在生产中使用此模式(模式是此处定义:AES/ECB/PKCS5Padding).

结果:


sharedKey: UT7PPJwX2fnYTazSOZAhxg==
keySpecReceived equals secretKey: true

代码:

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class Main {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        System.out.println("");
        // random key creation taken from 
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = new SecureRandom();
        int keyBitSize = 128; // aes keylength can be 128, 192 or 256 bit
        keyGenerator.init(keyBitSize, secureRandom);
        SecretKey k = keyGenerator.generateKey();
        // encode the key and then base64-encoding
        String sharedKey = Base64.getEncoder().encodeToString(k.getEncoded());
        System.out.println("sharedKey: " + sharedKey);

        // share this key with another party on a secure way
        String sharedKeyReceived = sharedKey; // simulates the receiving
        byte[] sharedKeyByteReceived = Base64.getDecoder().decode(sharedKeyReceived);
        SecretKeySpec kReceived = new SecretKeySpec(sharedKeyByteReceived, "AES");
        System.out.println("keySpecReceived equals secretKey: " + kReceived.equals(k));
    }
}