Rails:将256位校验和作为二进制存储在数据库中 [英] Rails: Storing a 256 bit checksum as binary in database

查看:128
本文介绍了Rails:将256位校验和作为二进制存储在数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将SHA-2 256位校验和存储在列中:

I'm trying to store a SHA-2 256 bit checksum in a column:

create_table :checksums do |t|
  t.binary :value, :null => false, :limit => 32
end

我将这样存储值:

c = Checksum.new
big_num = Digest::SHA2.new.update("some string to be checksum'd").hexdigest.to_i(16)
c.value = big_num

关于将big_num分配给c.value我得到:

On the assignment of big_num to c.value I get:

NoMethodError: undefined method `gsub' for #<Bignum:0x00000001ea48f8>

有人知道我在做什么错吗?

Anybody know what I'm doing wrong?

推荐答案

如果要将SHA2存储在二进制列中,则可能只想使用 digest 方法以获取原始数据SHA2字节:

If you're going to be storing your SHA2 in a binary column then you probably just want to use the digest method to get the raw SHA2 bytes:

big_num = Digest::SHA2.new.update("some string to be checksum'd").digest

您的SHA2是256位值(32字节),不适合Fixnum(由于内部记账位的原因,它使用的位数少于32位或64位),这就是为什么您在调用 .hexdigest.to_i(16)时得到Bignum的原因。二进制列实际上只是字节序列(即二进制 strings ),部分编码机制可能是使用 gsub 将字节转换为数据库期望的格式。您正在将Bignum分配给希望看到String且无法正常工作的东西。

Your SHA2 is a 256 bit value (32 bytes) and that won't fit in a Fixnum (which uses less than 32 or 64 bits due to internal bookkeeping bits), that's why you end up with a Bignum when you call .hexdigest.to_i(16). Binary columns are really just sequences of bytes (i.e. binary strings) and part of the encoding mechanism is probably using gsub to get the bytes into the format that the database expects. You're assigning a Bignum to something that expects to see a String and that doesn't work that well.

您还可以使用简单的字符串列(<< c $ c>:limit => 64 )存储 .hexdigest 值而不是32字节的二进制列。

You could also use a simple string column (with :limit=> 64) to store the .hexdigest value instead of a 32 byte binary column.

这篇关于Rails:将256位校验和作为二进制存储在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆