我正在尝试在java中实现AES 256位CBC算法。我想做这样的事情。 Click here
我在多个SO线程中使用以下程序,以下是我用来加密/解密的代码。根据@dave_thompson建议更新了代码,但是对于IV的长度仍然是相同的错误。
import java.security.AlgorithmParameters;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Scanner;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class EncryptionDecryption {
private static String salt;
private static int iterations = 65536 ;
private static int keySize = 256;
private static byte[] ivBytes = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,};
private static SecretKey secretKey;
public static void main(String []args) throws Exception {
Scanner in = new Scanner(System.in);
salt = getSalt();
String s = in.nextLine();
char[] message = s.toCharArray();
System.out.println("Message: " + String.valueOf(message));
System.out.println("Encrypted: " + encrypt(message));
System.out.println("Decrypted: " + decrypt(encrypt(message).toCharArray()));
}
public static String encrypt(char[] plaintext) throws Exception {
byte[] saltBytes = salt.getBytes();
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(plaintext, saltBytes, iterations, keySize);
secretKey = skf.generateSecret(spec);
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretSpec);
AlgorithmParameters params = cipher.getParameters();
byte[] encryptedTextBytes = cipher.doFinal(String.valueOf(plaintext).getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(encryptedTextBytes);
}
public static String decrypt(char[] encryptedText) throws Exception {
System.out.println(encryptedText);
byte[] encryptedTextBytes = DatatypeConverter.parseBase64Binary(new String(encryptedText));
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretSpec, new IvParameterSpec(ivBytes));
byte[] decryptedTextBytes = null;
try {
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return new String(decryptedTextBytes);
}
public static String getSalt() throws Exception {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[20];
sr.nextBytes(salt);
return new String(salt);
}
}
当前代码的问题向我显示以下错误,但如果我将IV更改回16位则可以正常工作。
以下是我所指的SO线程。
答案 0 :(得分:2)
CBC模式加密的IV大小与块大小相同。 AES是Rijndael的子集,具有某些限制。其中一个限制是块大小总是 128位。
在AES参数外使用时,Rijndael未标准化。这意味着它通常没有实现。 Oracle的Java没有在AES边界之外实现Rijndael。 Bouncy Castle确实如此,it doesn't expose higher block sizes to the outside。
所以你唯一能做的就是使用Rounndael - 所谓的 - Bouncy Castle提供商的轻量级API。基本上你会通过Bouncy的专有界面直接调用Bouncy Castle提供商的底层实现。
警告:以下代码使用静态(归零)密钥和IV。它仅用于演示块大小为256位的Rijndael密码。它不遵循(加密)最佳实践。
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.RijndaelEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
public class RijndaelTestJava {
private static final boolean FOR_ENCRYPTION = true;
public static void main(String[] args) throws Exception {
rijndael256BouncyLW();
rijndael256BouncyProvider();
}
private static void rijndael256BouncyLW() throws InvalidCipherTextException {
{
RijndaelEngine rijndael256 = new RijndaelEngine(256);
BufferedBlockCipher rijndael256CBC =
new BufferedBlockCipher(
new CBCBlockCipher(rijndael256));
KeyParameter key = new KeyParameter(new byte[256 / Byte.SIZE]);
rijndael256CBC.init(FOR_ENCRYPTION, new ParametersWithIV(key,
new byte[256 / Byte.SIZE]));
byte[] in = new byte[64]; // two blocks
byte[] out = new byte[64]; // two blocks
int off = rijndael256CBC.processBytes(in, 0, in.length, out, 0);
off += rijndael256CBC.doFinal(out, off);
System.out.println(Hex.toHexString(out));
}
}
private static void rijndael256BouncyProvider() throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException {
{
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("Rijndael/CBC/PKCS7Padding");
SecretKeySpec key = new SecretKeySpec(new byte[256 / Byte.SIZE],
"Rijndael");
IvParameterSpec iv = new IvParameterSpec(new byte[256 / Byte.SIZE]);
// throws an InvalidAlgorithmParameterException: IV must be 16 bytes long.
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] out = cipher.doFinal("owlsteead"
.getBytes(StandardCharsets.US_ASCII));
System.out.println(Hex.toHexString(out));
}
}
}
答案 1 :(得分:1)
IV应与 AES 的块大小相同,即128位(16字节)。
您在加密中定义的IV实际上没有传递给密码...因此密码会为您生成一个(即16字节)。
答案 2 :(得分:1)
好的,现在我们有一个特定的目标:AES-CBC(尽管你的示例数据只有一个块,因此CBC并不重要),以十六进制表示的128位密钥,(128位)IV全部为零,零填充(如果精确阻塞则省略)。
static void SO37248569() throws Exception {
// fixed key; in real use key should be securely provided or generated
String keyhex = "6c616d70736865657031323334353637";
// crude way of converting hex to bytes, better ways are possible
byte[] key = new BigInteger (keyhex,16).toByteArray();
if( key.length > 16 ) key = Arrays.copyOfRange (key, 1, key.length); // maybe signed
if( key.length != 16 ) throw new Exception ("key length wrong!");
// all-zero IV, only secure if key is unique every time
byte[] IV = new byte[16];
//
// fixed plaintext for example, in real use obtain as needed
byte[] plainbytes = "Hello world".getBytes();
// note: for ASCII-only data the Java default encoding is okay;
// if real data can or could contain other chars, specify a
// suitable encoding; "UTF-8" is good for most text-y data
//
// ENCRYPT: we need to add zero padding ourself since JCE doesn't do that
// Java makes this easy because arrays are initialized to all-zeros
if( plainbytes.length %16 !=0 )
plainbytes = Arrays.copyOf (plainbytes, (plainbytes.length /16 +1)*16);
//
Cipher aes = Cipher.getInstance ("AES/CBC/NoPadding");
aes.init (Cipher.ENCRYPT_MODE, new SecretKeySpec (key, "AES"), new IvParameterSpec (IV));
byte[] cipherbytes = aes.doFinal (plainbytes);
// crude way of converting bytes to hex, again better possible
System.out.println ("encrypt hex->" + new BigInteger (1,cipherbytes).toString(16));
// alternatively just write to a file and let other tools handle
//
// DECRYPT: assuming bytes read from file, or already converted from hex
//same as above: Cipher aes = Cipher.getInstance ("AES/CBC/NoPadding");
aes.init (Cipher.DECRYPT_MODE, new SecretKeySpec (key, "AES"), new IvParameterSpec (IV));
byte[] resultbytes = aes.doFinal (cipherbytes);
//
// now we need to remove the zero padding, which is ambiguous
// this will damage data that actually has trailing zero bytes
int i; for( i = resultbytes.length; --i>=0 && resultbytes[i]==0; ){}
resultbytes = Arrays.copyOf (resultbytes, i+1);
//
// for example just display, for real use adapt as desired
System.out.println ("decrypt chars->" + new String (resultbytes));
// see above about encoding
}
产生结果
encrypt hex->e6b426aca323815fd6583cbcc4293c8d
decrypt chars->Hello world