简体   繁体   中英

JAVA MySQL insert with AES_ENCRYPT fails java.sql.SQLException: Incorrect string value

I'm trying to take the values from a HTML form on a JSP and save them to a user table in MySQL with one of the fields encrypted on insert but I get the following error in the Tomcat logs

java.sql.SQLException: Incorrect string value: '\\xEF\\xA3H\\x013p...' I've read "Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC? and set the character encoding

ALTER DATABASE mydb CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
ALTER TABLE users CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 
ALTER TABLE users CHANGE phone phone VARCHAR(265) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_c

I haven't gone near the MySQL server ini file and changed the default character set there as in reality I will most likely not have access to this file and permission to change the values.

The query is as follows. The key is a simple string value similar to AbcD10Qs could it be my query in my model that is causing the issue?

String key=confUtil.encDeckey();

    String query
            = "INSERT INTO users (fName, lName, email,pwd,phone)"
            + "VALUES (?, ?, ?, ?, AES_ENCRYPT(?,?))";
    try {
        ps = connection.prepareStatement(query);
        ps.setString(1, user.getFName());
        ps.setString(2, user.getLName());
        ps.setString(3, user.getEmail());
        ps.setString(4, user.getPwd());
        ps.setString(5, user.getPhone());
        ps.setString(6,key);
        ps.executeUpdate();

I'm using a connection pool to manage the connection to the DB

private ConnectionPool() {
    try {
        InitialContext ic = new InitialContext();
        dataSource = (DataSource) ic.lookup("java:/comp/env/jdbc/testdb");
    } catch (NamingException e) {
        System.err.println(e);
    }
}

No character encoding set in the context.xml

  <Resource name="jdbc/medsdb" type="javax.sql.DataSource" auth="Container" 
        driverClassName="com.mysql.jdbc.Driver" 
        url="jdbc:mysql://localhost:3306/medsdb?autoReconnect=true" 
        username="testdbbuser" password="xxxxxxx" 
        logAbandoned="true" 
        removeAbandoned="true" removeAbandonedTimeout="60" 
        maxActive="100" maxIdle="30" maxWait="10000" />

https://dev.mysql.com/doc/refman/5.7/en/encryption-functions.html提及以下内容:“许多加密和压缩函数返回的字符串可能会导致结果包含任意字节值。如果要存储这些字符串结果,请使用具有VARBINARY或BLOB二进制字符串数据类型的列。这样可以避免因删除尾部空格或字符集转换而可能会更改数据值的潜在问题,例如如果您使用非二进制字符串数据类型(CHAR,VARCHAR ,TEXT)“尝试不要将VARCHAR用作“电话”的字段类型

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