用户密码加密存储

WEB应用如何存储用户密码

核心思路

  • 客户端传递md5散列后的明文密码
  • 服务端将明文进行BCrypt加密后再进行aes加密

后端代码

  • 依赖Hutool实现,Hutool文档
  • 工具类 PasswordUtils
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    public class PasswordUtils {

    /**
    * 检查明文密码与密文密码是否一致
    * plainText:明文密码,由客户端提供(前端提供的为明文进行md5加密后的,小写)
    * cipherText:密文密码,由数据库查询
    * aesKey:AES加密密钥,由系统配置获取
    *
    * @author 非羽Army
    **/
    public static Boolean checkPassword(String plainText, String cipherText, String aesKey) {
    return BCrypt.checkpw(
    (new Digester(DigestAlgorithm.SHA512)).digestHex(plainText.toLowerCase(), StandardCharsets.UTF_8)
    , (new SymmetricCrypto(SymmetricAlgorithm.AES, aesKey.getBytes(StandardCharsets.UTF_8))).decryptStr(cipherText)
    );
    }

    /**
    * 生成密码
    * plainText:明文密码,由客户端提供(前端提供的为明文进行md5加密后的,小写)
    * aesKey:AES加密密钥,由系统配置获取
    *
    * @author 非羽Army
    **/
    public static String generatePassword(String plainText, String aesKey) {
    return (new SymmetricCrypto(SymmetricAlgorithm.AES, aesKey.getBytes(StandardCharsets.UTF_8))).encryptHex(
    BCrypt.hashpw(
    (new Digester(DigestAlgorithm.SHA512)).digestHex(
    plainText.toLowerCase(), StandardCharsets.UTF_8
    )
    )
    );
    }
    }
  • 数据库存储
    • MySQL: varchar(128)