在Ruby中将0-F的字符串转换为字节数组

时间:2022-08-03 21:44:27

I am attempting to decrypt a number encrypted by another program that uses the BouncyCastle library for Java.

我试图解密由另一个使用BouncyCastle库for Java的程序加密的数字。

In Java, I can set the key like this: key = Hex.decode("5F3B603AFCE22359");

在Java中,我可以像这样设置密钥:key = Hex.decode(“5F3B603AFCE22359”);

I am trying to figure out how to represent that same step in Ruby.

我试图弄清楚如何在Ruby中表示同样的步骤。

2 个解决方案

#1


33  

To get Integer — just str.hex. You may get byte array in several ways:

得到整数 - 只是str.hex。您可以通过多种方式获得字节数组:

str.scan(/../).map(&:hex)
[str].pack('H*').unpack('C*')
[str].pack('H*').bytes.to_a

See another options for pack/unpack here: http://ruby-doc.org/core/classes/String.html#method-i-unpack

请在此处查看打包/解压缩的其他选项:http://ruby-doc.org/core/classes/String.html#method-i-unpack

And examples here: http://www.codeweblog.com/ruby-string-pack-unpack-detailed-usage/

这里有例子:http://www.codeweblog.com/ruby-string-pack-unpack-detailed-usage/

#2


2  

For a string str:

对于字符串str:

"".tap {|binary| str.scan(/../) {|hn| binary << hn.to_i(16).chr}}

#1


33  

To get Integer — just str.hex. You may get byte array in several ways:

得到整数 - 只是str.hex。您可以通过多种方式获得字节数组:

str.scan(/../).map(&:hex)
[str].pack('H*').unpack('C*')
[str].pack('H*').bytes.to_a

See another options for pack/unpack here: http://ruby-doc.org/core/classes/String.html#method-i-unpack

请在此处查看打包/解压缩的其他选项:http://ruby-doc.org/core/classes/String.html#method-i-unpack

And examples here: http://www.codeweblog.com/ruby-string-pack-unpack-detailed-usage/

这里有例子:http://www.codeweblog.com/ruby-string-pack-unpack-detailed-usage/

#2


2  

For a string str:

对于字符串str:

"".tap {|binary| str.scan(/../) {|hn| binary << hn.to_i(16).chr}}