如何编写一个Java函数来实现基本的加密解密功能?
发布时间:2023-08-21 11:06:41
Java提供了很多加密解密的API,可以使用Java的加密库实现基本的加密解密功能。下面是一个简单的Java函数实现基本的加密解密功能的示例:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class EncryptionUtils {
private static final String ALGORITHM = "AES";
private static final String KEY = "mysecretkey";
public static String encrypt(String plainText) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);
}
public static void main(String[] args) throws Exception {
String plainText = "Hello, World!";
System.out.println("Plain Text: " + plainText);
String encryptedText = encrypt(plainText);
System.out.println("Encrypted Text: " + encryptedText);
String decryptedText = decrypt(encryptedText);
System.out.println("Decrypted Text: " + decryptedText);
}
}
在上面的代码中,我们使用了AES对称加密算法来实现加密和解密功能。KEY是一个密钥,你可以根据自己的需求设置密钥。encrypt函数接受一个明文字符串作为输入,并返回加密后的密文字符串。decrypt函数接受一个密文字符串作为输入,并返回解密后的明文字符串。
在main函数中,我们演示了如何使用这些函数进行加密和解密操作。我们先使用encrypt函数将明文字符串加密,然后使用decrypt函数将密文字符串解密,并将解密后的明文字符串输出到控制台。
请注意,上述示例只是一个简单的实现,实际中可能需要更复杂的加密算法和密钥管理方案来确保安全性。加密解密函数的实现也可以根据具体需求进行扩展和优化。
