gpt4 book ai didi

java - 使用 iv/pass/salt/iterations 进行 AES 加密

转载 作者:行者123 更新时间:2023-12-02 01:57:28 26 4
gpt4 key购买 nike

以下 groovy/java 代码使用密码和 iv 对给定字符串进行 ecnrypt。

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;

byte[] iv = "1234567812345678";
byte[] keyb = "ABCDEFGHIJKLMNOPQRSTUVWX";

IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeySpec skey = new SecretKeySpec(keyb, "AES");

Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
ci.init(Cipher.ENCRYPT_MODE, skey, ivspec);

String plainText = "Encrypt this text with AES - MODE CBC";

byte[] input = plainText.getBytes("UTF-8");
byte[] encoded = ci.doFinal(input);

System.out.println(encoded.encodeBase64().toString());

我正在寻找一些有关如何在流程中添加迭代的指导。

最佳答案

我相信您正在考虑基于密码的加密 (PBE)。要在 Java 中执行此操作,您需要像这样的东西 ( source ):

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public static byte[] encrypt(final byte[] data, final char[] password,
final byte[] salt, final int noIterations) {
try {
final String method = "PBEWITHHMACSHA512ANDAES_256";
final SecretKeyFactory kf = SecretKeyFactory.getInstance(method);
final PBEKeySpec keySpec = new PBEKeySpec(password);
final SecretKey key = kf.generateSecret(keySpec);
final Cipher ciph = Cipher.getInstance(method);
final PBEParameterSpec params = new PBEParameterSpec(salt, noIterations);
return ciph.doFinal(data);
} catch (final Exception e) {
// best not to let the encryption error bubble out
throw new RuntimeException("Spurious encryption error");
}
}

关于java - 使用 iv/pass/salt/iterations 进行 AES 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52112918/

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