Bouncy castleを使用して暗号化と復号化を試みています。私は以下のエラーに陥っています。修正したり、暗号化し、弾む城に「メイン」java.security.InvalidKeyExceptionスレッドでAES Bouncy Castle-無効なパラメータがAESに渡されるinit-org.bouncycastle.crypto.params.ParametersWithIV
例外を使用して復号化するために任意のより良い方法がある方法:AESの初期化に渡された無効なパラメータが - org.bouncycastle.crypto.params.ParametersWithIV at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineInit(不明なソース) at javax.crypto.Cipher.init(Cipher.java:1394) at com.test.PBE.encrypt(PBE.java :39) com.test.PBE.main(PBE.java:26)
でこれは私のコード
ですimport java.security.SecureRandom;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class PBE {
private static final String salt = "A long, but constant phrase that will be used each time as the salt.";
private static final int iterations = 2000;
private static final int keyLength = 256;
private static final SecureRandom random = new SecureRandom();
public static void main(String [] args) throws Exception {
Security.insertProviderAt(new BouncyCastleProvider(), 1);
String passphrase = "The quick brown fox jumped over the lazy brown dog";
String plaintext = "hello world";
byte [] ciphertext = encrypt(passphrase, plaintext);
String encryptedText=ciphertext.toString();
System.out.println("text::"+encryptedText);
String recoveredPlaintext = decrypt(passphrase, encryptedText);
System.out.println(recoveredPlaintext);
}
private static byte [] encrypt(String passphrase, String plaintext) throws Exception {
SecretKey key = generateKey(passphrase);
Cipher cipher = Cipher.getInstance("AES/CTR/NOPADDING");
cipher.init(Cipher.ENCRYPT_MODE, key, generateIV(cipher), random);
return cipher.doFinal(plaintext.getBytes());
}
private static String decrypt(String passphrase, String encryptedText) throws Exception {
byte[] ciphertext=encryptedText.getBytes();
SecretKey key = generateKey(passphrase);
Cipher cipher = Cipher.getInstance("AES/CTR/NOPADDING");
cipher.init(Cipher.DECRYPT_MODE, key, generateIV(cipher), random);
return new String(cipher.doFinal(ciphertext));
}
private static SecretKey generateKey(String passphrase) throws Exception {
PBEKeySpec keySpec = new PBEKeySpec(passphrase.toCharArray(), salt.getBytes(), iterations, keyLength);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWITHSHA256AND256BITAES-CBC-BC");
return keyFactory.generateSecret(keySpec);
}
private static IvParameterSpec generateIV(Cipher cipher) throws Exception {
byte [] ivBytes = new byte[cipher.getBlockSize()];
random.nextBytes(ivBytes);
return new IvParameterSpec(ivBytes);
}
}
しかし、私はバイト[]で同じエラーが発生しています – TechEnthu
私は文字列を使用する方法が必要です – TechEnthu