在 MySQL 中存储 SHA1 哈希值

Storing SHA1 hash values in MySQL(在 MySQL 中存储 SHA1 哈希值)
本文介绍了在 MySQL 中存储 SHA1 哈希值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想将 SHA1 散列的结果存储在 MySQL 数据库中时,我遇到了一个简单的问题:

I have a simple question which occured when I wanted to store the result of a SHA1 hash in a MySQL database:

VARCHAR 字段应该在多长时间内存储散列结果?

How long should the VARCHAR field be in which I store the hash's result?

推荐答案

我会使用 VARCHAR 来处理可变长度的数据,但不会使用固定长度的数据.因为 SHA-1 值总是 160 位长,VARCHAR 只会浪费 固定长度字段长度的附加字节.

I would use VARCHAR for variable length data, but not with fixed length data. Because a SHA-1 value is always 160 bit long, the VARCHAR would just waste an additional byte for the length of the fixed-length field.

而且我也不会存储 SHA1 正在返回.因为它每个字符只使用 4 位,因此需要 160/4 = 40 个字符.但是如果您使用每个字符 8 位,您将只需要一个 160/8 = 20 个字符的长字段.

And I also wouldn’t store the value the SHA1 is returning. Because it uses just 4 bit per character and thus would need 160/4 = 40 characters. But if you use 8 bit per character, you would only need a 160/8 = 20 character long field.

所以我推荐你使用 BINARY(20)UNHEX 函数将 SHA1 值转换为二进制.

So I recommend you to use BINARY(20) and the UNHEX function to convert the SHA1 value to binary.

我比较了 BINARY(20)CHAR(40) 的存储要求.

I compared storage requirements for BINARY(20) and CHAR(40).

CREATE TABLE `binary` (
    `id` int unsigned auto_increment primary key,
    `password` binary(20) not null
);
CREATE TABLE `char` (
    `id` int unsigned auto_increment primary key,
    `password` char(40) not null
);

百万条记录 binary(20) 占用 44.56M,而 char(40) 占用 64.57M.InnoDB 引擎.

With million of records binary(20) takes 44.56M, while char(40) takes 64.57M. InnoDB engine.

这篇关于在 MySQL 中存储 SHA1 哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)