Java Cipher
时间: 2023-10-28 20:04:52 浏览: 56
The Java Cipher class provides encryption and decryption functionality in Java. It uses a cryptographic algorithm to perform the encryption and decryption operations. Some common symmetric encryption algorithms include AES, DES, and Blowfish.
To use the Cipher class, you first need to create a Cipher object by specifying the encryption algorithm, mode of operation, and padding scheme. Once you have created the Cipher object, you can use it to encrypt or decrypt data.
Here's an example of how to use the Cipher class to encrypt and decrypt data using the AES algorithm:
```java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class CipherExample {
public static void main(String[] args) throws Exception {
String plainText = "This is some plain text";
// Generate a secret key for the AES algorithm
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
SecretKey secretKey = keyGen.generateKey();
// Create a Cipher object using the AES algorithm
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// Encrypt the plain text using the secret key
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedText = cipher.doFinal(plainText.getBytes());
// Decrypt the encrypted text using the same secret key
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedText = cipher.doFinal(encryptedText);
System.out.println("Plain text: " + plainText);
System.out.println("Encrypted text: " + new String(encryptedText));
System.out.println("Decrypted text: " + new String(decryptedText));
}
}
```
In this example, we first generate a secret key using the AES algorithm with a key size of 256 bits. We then create a Cipher object using the AES algorithm with CBC mode and PKCS5Padding padding scheme. We use this Cipher object to encrypt the plain text by calling the doFinal method with the Cipher.ENCRYPT_MODE parameter. We then decrypt the encrypted text using the same Cipher object by calling the doFinal method with the Cipher.DECRYPT_MODE parameter.
Note that you should always use a secure key size and algorithm when encrypting sensitive data. Also, be sure to store the secret key securely and never share it with unauthorized parties.