java写一个加密算法
时间: 2023-05-24 16:03:32 浏览: 62
A:Java中有很多种加密算法,比如DES、AES等。下面是一个使用AES算法加密和解密字符串的例子:
```
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
public class AESEncrypter {
private static final String ALGORITHM = "AES";
private static final int KEY_SIZE = 128;
/**
* 生成随机密钥
* @return
* @throws Exception
*/
public static byte[] generateKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(KEY_SIZE);
Key key = keyGenerator.generateKey();
return key.getEncoded();
}
/**
* 加密
* @param plainText 明文
* @param key 密钥
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] plainText, byte[] key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher.doFinal(plainText);
}
/**
* 解密
* @param cipherText 密文
* @param key 密钥
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] cipherText, byte[] key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
return cipher.doFinal(cipherText);
}
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!";
byte[] key = generateKey();
byte[] cipherText = encrypt(plainText.getBytes(), key);
byte[] decryptedText = decrypt(cipherText, key);
System.out.println("原文:" + plainText);
System.out.println("密钥:" + new String(key));
System.out.println("密文:" + new String(cipherText));
System.out.println("解密后:" + new String(decryptedText));
}
}
```
在这个例子中,我们使用了AES算法,密钥长度为128位。我们提供了三个方法:generateKey用于生成随机密钥,encrypt用于加密,decrypt用于解密。使用例子中的main方法测试这个加密算法。