数据库java加密字符串不能存储在数据库中
尝试使用javax。加密库,用于加密字符串并将其存储在数据库(Oracle)中。稍后我需要解密这个字符串,所以我需要一个双向算法
问题是数据库似乎不接受该方法创建的某些加密字符。我们正在将数据库迁移到新服务器之间。旧数据库使用US7ASCII字符集,而新数据库使用AL32UTF8。当我将加密字符串放入数据库时,数据库只是将它们转换为问号(?)在US7ASCII数据库中。它似乎在AL32UTF8数据库中存储得很好
所以,我必须使这个交叉兼容。在使用getBytes()方法时,我尝试向它发送不同的StandardCharset值,但似乎没有帮助。也许我错过了什么。有没有什么方法可以让我以不同的方式达到预期的效果
这是我生成密码文本的代码。从StackOverflow上的另一个帖子修改
import java.io.PrintStream;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
public class test
{
public static void main(String[] args)
throws Exception
{
//byte[] encryptionKey = "Es6XYPkgCV75J95Y".getBytes(StandardCharsets.UTF_8);
byte[] encryptionKey = "Es6XYPkgCV75J95Y".getBytes(StandardCharsets.ISO_8859_1);
//byte[] plainText = args[0].getBytes(StandardCharsets.UTF_8);
byte[] plainText = args[0].getBytes(StandardCharsets.ISO_8859_1);
MyCrypto aes = new MyCrypto(encryptionKey);
byte[] cipherText = aes.encrypt(plainText);
byte[] decryptedCipherText = aes.decrypt(cipherText);
System.out.println(new String(plainText));
System.out.println(new String(cipherText));
System.out.println(new String(decryptedCipherText));
}
}
class MyCrypto
{
private byte[] key;
private static final String ALGORITHM = "AES";
public MyCrypto(byte[] key)
{
this.key = key;
}
/**
* Encrypts the given plain text
*
* @param plainText The plain text to encrypt
*/
public byte[] encrypt(byte[] plainText) throws Exception
{
SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(plainText);
}
/**
* Decrypts the given byte array
*
* @param cipherText The data to decrypt
*/
public byte[] decrypt(byte[] cipherText) throws Exception
{
SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(cipherText);
}
}
# 1 楼答案
当您加密数据时,您将其转换为二进制数据。听起来像是试图将其存储为字符数据,这是一个坏主意
你真的有两个选择
使用二进制到文本方案(如Base64)对加密的二进制数据进行编码。然后可以将编码数据存储为字符数据。当您想要检索它时,您读取字符数据并在解密之前解码(文本到二进制)
将加密的二进制数据存储为二进制(例如作为BLOB)