简体   繁体   中英

PersistenceException:ERROR: invalid byte sequence for encoding “UTF8”

I am working on PostgreSQL and getting below error during update statement execution from java code.

ERROR: invalid byte sequence for encoding "UTF8": 0x00

The code snippet for password encrption is :

StringBuilder encryptionKey = new StringBuilder().append(newPassword).append(userEmail).append(userEmail).append(userEmail);
AdvancedEncryptionStandard aes = new AdvancedEncryptionStandard(encryptionKey.toString().getBytes(StandardCharsets.UTF_8));
newEncryptedPwd =  new String(aes.encrypt(newPassword.getBytes(StandardCharsets.UTF_8)));
EntityManager em = EntityManagerUtil.getEntityManager(schemaName);
EntityManagerUtil.beginTransaction(schemaName);
Query query = em.createQuery("UPDATE User um SET um.password=:newPassword WHERE um.loginId=:userID");
query.setParameter("userID", userName);
query.setParameter("newPassword", newEncryptedPwd);
query.executeUpdate();

Encrypt function is as below:

public byte[] encrypt(byte[] plainText) throws Exception
    {
        SecretKeySpec secretKey = new SecretKeySpec(key,0,16,'AES');
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(plainText);
    }
public AdvancedEncryptionStandard(byte[] key)
    {
        this.key = key;
    }

I have checked client_encoding by show client_encoding command and it is showing UTF-8.

Can someone give me pointer on resolving this issue? I have gone through the suggestions provided in other threads but none helped.

0 actually is invalid UTF8. UTF8 contains æ, it contains ™, but none of what it contains has code point 0.

Your problem is that you're trying to store arbitrary binary data as though it were UTF8-encoded text. Don't. If you encrypt something, the encryption will have hidden its nature (that's the job description for encryption) so it was an integer, you no longer can store it in an integer column, it if was text you no longer can store it in a text column. What you have is just an array of bytes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM