Java函数,用于加密和解密数据
发布时间:2023-08-30 19:49:40
Java中可以使用各种加密算法对数据进行加密和解密。下面是一个简单的例子,使用Java的AES加密算法对数据进行加密和解密。
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
public class EncryptionUtils {
private static final String ALGORITHM = "AES";
public static byte[] encrypt(String text, String password) throws Exception {
SecretKeySpec secretKeySpec = generateKey(password);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
}
public static String decrypt(byte[] encryptedData, String password) throws Exception {
SecretKeySpec secretKeySpec = generateKey(password);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedData = cipher.doFinal(encryptedData);
return new String(decryptedData, StandardCharsets.UTF_8);
}
private static SecretKeySpec generateKey(String password) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
return new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8), ALGORITHM);
}
public static void main(String[] args) throws Exception {
String plainText = "Hello, World!";
String password = "MySecretPassword";
byte[] encryptedData = encrypt(plainText, password);
String decryptedText = decrypt(encryptedData, password);
System.out.println("Encrypted Text: " + new String(encryptedData, StandardCharsets.UTF_8));
System.out.println("Decrypted Text: " + decryptedText);
}
}
在上面的示例中,我们使用AES算法对"Hello, World!"这个字符串进行加密和解密。加密和解密的密钥都是"MySecretPassword",可以根据需要进行更改。
在encrypt方法中,我们首先生成了一个256位的密钥(根据需要可以调整密钥长度),然后使用该密钥初始化Cipher对象,并将其设置为加密模式。接下来,我们使用cipher.doFinal方法对原始文本进行加密,并返回加密后的字节数组。
在decrypt方法中,我们使用相同的密钥和Cipher对象将其设置为解密模式,并对加密后的字节数组进行解密。然后我们将解密后的字节数组转换为字符串,并返回解密后的原始文本。
在main方法中,我们调用encrypt方法对明文进行加密,并将加密后的数据作为字节数组打印出来。然后,我们调用decrypt方法对加密后的数据进行解密,并将解密后的原始文本打印出来。
注意:在实际使用中,为了保证数据的安全性,我们还需要对密钥进行存储和管理,以及使用更高级的加密算法和安全措施。上面的示例仅供参考和初步了解加密和解密的基本概念和实现方法。
