aes 256 OFB java实现
时间: 2023-09-03 17:12:24 浏览: 48
下面是AES 256 OFB模式的Java实现示例:
```java
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESOFBExample {
public static void main(String[] args) throws Exception {
String plainText = "This is a secret message";
System.out.println("Plain Text: " + plainText);
// Generate a 256-bit AES key
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
SecretKey secretKey = keyGen.generateKey();
byte[] keyBytes = secretKey.getEncoded();
// Generate a random initialization vector
SecureRandom random = new SecureRandom();
byte[] ivBytes = new byte[16];
random.nextBytes(ivBytes);
// Create the Cipher object and configure it for OFB mode with AES encryption
Cipher cipher = Cipher.getInstance("AES/OFB/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
// Encrypt the plain text
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
System.out.println("Encrypted Text: " + new String(encryptedBytes));
// Decrypt the encrypted text
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
System.out.println("Decrypted Text: " + new String(decryptedBytes));
}
}
```
上述代码中,我们首先使用Java的`KeyGenerator`类生成一个256位的AES密钥。然后,我们使用`SecureRandom`类生成一个随机的16字节的初始化向量。
接下来,我们创建一个`Cipher`对象,并将其配置为使用AES加密的OFB模式。然后,我们使用生成的密钥和初始化向量初始化`Cipher`对象,并使用`doFinal`方法对明文进行加密。
最后,我们再次使用相同的密钥和初始化向量初始化`Cipher`对象,并使用`doFinal`方法对密文进行解密。