Java 使用AES和共享密码加密文件

Java 使用AES和共享密码加密文件,java,encryption,aes,Java,Encryption,Aes,我想用AES加密/解密,使用sharedpasswod,我的代码与相同 链接代码工作正常,但没有共享密码 如何将共享密码添加到以下实现中 我需要像这样的东西 String shared="xxx..";//some password with 16 digits length 可能吗 并将此共享密码添加到加密中。非常重要的是,用于AES加密的密钥不容易猜测,因此在许多实现中,密钥是随机生成的。密钥本身是16(128位)、24(192位)或32(256位)字节长度的字节数组,

我想用AES加密/解密,使用sharedpasswod,我的代码与相同

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

如何将共享密码添加到以下实现中

我需要像这样的东西

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


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

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

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

小示例展示了安全生成不同长度的随机密码的方法(示例仅使用128位密钥长度,对其进行编码并将其解码回密钥-原始密钥k与重新生成的密钥k进行比较

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

结果:

https://stackoverflow.com/questions/62782129/encrypt-files-with-aes-with-shared-password
sharedKey: UT7PPJwX2fnYTazSOZAhxg==
keySpecReceived equals secretKey: true
代码:


您链接到的算法使用一个随机密钥,
k
。您应该能够调用
byte[]keyBytes=k.getEncoded()
,然后您可以将
keyBytes
转换为Base64,以人类可读的形式将其共享。
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("https://stackoverflow.com/questions/62782129/encrypt-files-with-aes-with-shared-password");
        // random key creation taken from https://stackoverflow.com/a/41414233/9114020
        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));
    }
}