使用java.util.Base64.getDecoder()解码后的奇怪字符

时间:2018-08-26 16:40:25

标签: java jpa encryption base64 eclipselink

我正在尝试加密数据库中的某些用户数据,然后在向用户显示时将其递减

我正在使用JPA,Eclipse链接2.7.1和M​​YSql 5.6进行此操作

用户实体如下所示:

@Entity
@Cacheable(false)
@Table(name = "user_table")
public class User implements Serializable {

// some fields
    @Lob
    @Column(name = "about_me")
    @Convert(converter = EncryptorConverter.class)
    String aboutMe;

// setters and getters
}

下面是EncryptorConverter.class

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import java.util.*;

@Converter

public class EncryptorConverter implements javax.persistence.AttributeConverter<String, String> {

    String key = "************"; // 128 bit key
    String initVector = "**************"; // 16 bytes IV
    IvParameterSpec iv;
    SecretKeySpec skeySpec;
    static Cipher cipher;
    static Cipher deipher;

    private static final Logger LOG = Logger.getLogger(
            EncryptorConverter.class.getName());


    public EncryptorConverter() {
        try {
            iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            deipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            deipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, ex.getMessage(), ex);
        }

    }


    @Override
    public String convertToDatabaseColumn(String attribute) {

        if (attribute == null) {
            return "";
        }
        try {
            byte[] encrypted = cipher.doFinal(attribute.getBytes("UTF-8"));
            return java.util.Base64.getEncoder().encodeToString(encrypted);
        } catch (BadPaddingException e) {
            // do nothing
        } catch (javax.crypto.IllegalBlockSizeException e) {
            // do nothing
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, ex.getMessage(), ex);
        }

        return "";
    }

    @Override
    public String convertToEntityAttribute(String dbData) {

        if (dbData == null) {
            return "";
        }
        try {
            byte[] original = deipher.doFinal(java.util.Base64.getDecoder().decode(dbData.getBytes("UTF-8")));
            return new String(original, "UTF-8");
        } catch (javax.crypto.IllegalBlockSizeException e) {
            // do nothing
        } catch (BadPaddingException e) {
            // do nothing
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, ex.getMessage(), ex);
        }

        return "";
    }

}

我的问题有时是,当我从aboutMe实体读取解码后的user字段时,看起来像是这样的奇怪字符 “��t����a:i3��5�o”,有时看起来很好,没有任何奇怪的字符。

解码步骤有什么问题吗?

非常感谢您的帮助。

0 个答案:

没有答案