gpt4 book ai didi

java - RIJNDAEL 256 CBC加密与Java中的IV

转载 作者:行者123 更新时间:2023-12-01 20:17:58 25 4
gpt4 key购买 nike

我有一个进行 Rijndael 加密的 PHP 代码的引用。我想将它转换为java代码,我尝试了几个例子,但没有一个对我有用。这是 php 代码:

$initialisationVector = hash("sha256", utf8_encode($myiv), TRUE);
$key = hash("sha256", utf8_encode($mykey), TRUE);
$encryptedValue = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256,$encryptKey, utf8_encode($mydata), MCRYPT_MODE_CBC, $initialisationVector));

这是我的 java 代码,抛出: key 长度不是 128/160/192/224/256 位

public static String encrypt() throws Exception{
String myiv = "somevalue";
String mykey = "somevalue";
String mydata = "somevalue";
String new_text = "";

RijndaelEngine rijndael = new RijndaelEngine(256);
CBCBlockCipher cbc_rijndael = new CBCBlockCipher(rijndael);
ZeroBytePadding c = new ZeroBytePadding();
PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(cbc_rijndael, c);

byte[] iv_byte = sha256(myiv);

byte[] givenKey = sha256(mykey);

CipherParameters keyWithIV = new ParametersWithIV(new KeyParameter(givenKey), iv_byte);

pbbc.init(true, keyWithIV);
byte[] plaintext = mydata.getBytes(Charset.forName("UTF-8"));
byte[] ciphertext = new byte[pbbc.getOutputSize(plaintext.length)];
int offset = 0;
offset += pbbc.processBytes(plaintext, 0, plaintext.length, ciphertext, offset);
offset += pbbc.doFinal(ciphertext, offset);
new_text = new String(new Base64().encode(ciphertext), Charset.forName("UTF-8"));
System.out.println(new_text);
return new_text;
}

public static byte[] sha256(String input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] messageDigest = md.digest(input.getBytes(Charset.forName("UTF-8")));
return messageDigest;
}

我不太擅长密码学。提前致谢!

最佳答案

错误消息很明确:“初始化 vector 的长度必须与 block 大小相同”。您指定 256 位(32 字节) block 大小,请验证 iv_byte 是否为 32 字节。

有几个问题:

  1. 对于 IV 从哈希中获取字节,将字节传递给加密函数,BigInteger 在其中没有位置。

  2. sha256(appId)提供了256位 key ,直接使用即可。

以下不需要,sha256的结果是256位:

final int keysize = 256;
byte[] keyData = new byte[keysize];
System.arraycopy(givenKey, 0, keyData, 0, Math.min(givenKey.length, keyData.length));
  • sha256(appId)提供了256位 key ,直接使用即可。
  • 不需要以下内容:

    final int keysize = 256; 
    byte[] keyData = new byte[keysize];
    System.arraycopy(givenKey, 0, keyData, 0, Math.min(givenKey.length, keyData.length));
  • mcrypt“MCRYPT_RIJNDAEL_256”指定 256 位 block 大小,这意味着它不是 AES,“MCRYPT_RIJNDAEL_128”是应使用的 AES。

  • mcrypt 使用非标准空填充,需要进行调整。

  • 使用 SHA-256 哈希不够安全,请使用密码派生函数,例如 PBKDF2。

  • 关于java - RIJNDAEL 256 CBC加密与Java中的IV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45442114/

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