我有一个用于加密字符串(令牌)的 PHP 代码。我需要生成此令牌并调用旧后端 API。后端 API 会解密并验证它,然后才允许访问 API。我们正在用 Java 构建客户端应用程序。所以这段代码需要用Java来实现。
$stringToEncode="****String which needs to be encrypted. This string length is multiple of 32********************";
$key="32ByteKey-asdcxzasdsadasdasdasda";
echo base64_encode(
mcrypt_encrypt(
MCRYPT_RIJNDAEL_256,
$key,
$stringToEncode,
MCRYPT_MODE_CBC,
$key
)
);
这里 IV 与 key 相同。我尝试使用以下 Java 代码使用“org.bouncycastle.crypto”
private static void encrypt(String key, String data) throws InvalidCipherTextException {
byte[] givenKey = key.getBytes(Charset.forName("ASCII"));
final int keysize = 256;
byte[] keyData = new byte[keysize / Byte.SIZE];
System.arraycopy(givenKey, 0, keyData, 0, Math.min(givenKey.length, keyData.length));
KeyParameter keyParameter = new KeyParameter(keyData);
BlockCipher rijndael = new RijndaelEngine(256);
ZeroBytePadding c = new ZeroBytePadding();
PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(rijndael, c);
CipherParameters ivAndKey = new ParametersWithIV(keyParameter, key.getBytes(Charset.forName("ASCII")));
pbbc.init(true, ivAndKey);
byte[] plaintext = data.getBytes(Charset.forName("UTF8"));
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);
System.out.println("Encrypted: " + Base64.getEncoder().encodeToString(ciphertext));
}
但低于例外 -
Exception in thread "main" java.lang.IllegalArgumentException: invalid parameter passed to Rijndael init - org.bouncycastle.crypto.params.ParametersWithIV
动漫人物