gpt4 book ai didi

java - AES加密和解密Java

转载 作者:太空宇宙 更新时间:2023-11-04 13:15:13 26 4
gpt4 key购买 nike

我正在使用 AES 加密字符串,并想在其他电脑上解密它。如果我在同一台电脑上执行,加密和解密就可以工作。但为了在其他电脑上解密,我的加密算法正在生成一个“密码”,另一端解密需要该“密码”以及 key 。我不知道如何将密码传输到另一端。

这是我的代码

 public class AESCrypt {

static String plainText;
static byte[] plainBytesDecrypted = new byte[1024];
static byte[] cipherBytes = new byte[1024];
static SecretKey key;
static Cipher cipher;

public AESCrypt() throws NoSuchAlgorithmException {
KeyGenerator generator = KeyGenerator.getInstance("AES");

generator.init(128);
key = generator.generateKey();

}

public static byte[] encryption(String plainBytes) {

try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherBytes = cipher.doFinal(plainBytes.getBytes());
System.out.println("Encrypted data : " + new String(cipherBytes));

} catch (Exception ex) {
ex.printStackTrace();
}
return cipherBytes;
}

private static String bytesToHex(byte[] hash) {

return DatatypeConverter.printHexBinary(hash);

}

public static String Decryption() throws InvalidKeyException, IllegalBlockSizeException, InvalidAlgorithmParameterException, BadPaddingException {

cipher.init(Cipher.DECRYPT_MODE, key, cipher.getParameters());
plainBytesDecrypted = cipher.doFinal(cipherBytes);

System.out.println("Decrypted data : " + new String(plainBytesDecrypted));

return (new String(plainBytesDecrypted));
}
}

最佳答案

一般来说,您有 3 个选择:

  • 对密码/模式/填充进行硬编码,以便双方都知道您始终使用相同的格式。
  • 在 secret 消息之前发送密码/模式/填充,以便对方知道要初始化什么密码。
  • 使用现有协议(protocol),该协议(protocol)已经为您提供了所有这些内容,并且可以安全地执行。例如,您可以在 TLS 连接内发送数据。

关于java - AES加密和解密Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33603653/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com