Android 使用对称加密返回String详细代码
下面是一个使用对称加密算法(AES)对字符串进行加密和解密的示例代码:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class SymmetricEncryptionExample {
private static final String KEY = "ThisIsASecretKey";
private static final String ALGORITHM = "AES";
public static void main(String[] args) {
String originalString = "Hello, World!";
System.out.println("Original string: " + originalString);
String encryptedString = encrypt(originalString);
System.out.println("Encrypted string: " + encryptedString);
String decryptedString = decrypt(encryptedString);
System.out.println("Decrypted string: " + decryptedString);
}
public static String encrypt(String value) {
try {
SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(value.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(String encryptedValue) {
try {
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(encryptedValue));
return new String(decryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
这段代码使用了AES对称加密算法进行加密和解密操作。在encrypt方法中,首先创建一个SecretKeySpec对象,使用密钥字符串和算法名称作为参数。然后创建一个Cipher对象,使用Cipher.ENCRYPT_MODE模式和密钥初始化。接下来,调用cipher.doFinal方法将字符串转换为加密的字节数组,并使用Base64类将字节数组转换为字符串。最后,返回加密后的字符串。
在decrypt方法中,首先创建一个SecretKeySpec对象,使用密钥字符串和算法名称作为参数。然后创建一个Cipher对象,使用Cipher.DECRYPT_MODE模式和密钥初始化。接下来,调用cipher.doFinal方法将加密字符串转换为解密的字节数组,并使用new String构造函数将字节数组转换为字符串。最后,返回解密后的字符串。
注意:这段代码中使用的密钥是一个硬编码的字符串,实际应用中应该使用更安全的密钥管理方式,如密钥库或密钥管理服务
原文地址: https://www.cveoy.top/t/topic/irG0 著作权归作者所有。请勿转载和采集!