Module: BytesManipulation
- Included in:
- Connection, Crypto
- Defined in:
- lib/bytes_manip.rb
Overview
Convenience methods to manipulate bytes.
Instance Method Summary collapse
-
#bs_rotate(bs, n = 1) ⇒ Object
Rotate a byte string by n bytes to the right.
-
#bs_xor(bs1, bs2) ⇒ Object
Xors together two byte strings of the same length.
-
#desfire_crc(data) ⇒ Object
DESFire-specific CRC algorithm taking a byte string as input and returning a byte string of length 2 as output.
-
#to_hex_array(array) ⇒ Object
Converts a byte array to an array holding strings representing the numbers in base 16.
-
#to_le_array(num, n) ⇒ Object
Converts a number to a little-endian array of n bytes.
Instance Method Details
#bs_rotate(bs, n = 1) ⇒ Object
Rotate a byte string by n bytes to the right. n can be negative, and efault to 1.
31 32 33 |
# File 'lib/bytes_manip.rb', line 31 def bs_rotate(bs, n=1) bs.unpack('C*').rotate(n).pack('C*') end |
#bs_xor(bs1, bs2) ⇒ Object
Xors together two byte strings of the same length.
20 21 22 23 24 25 26 27 |
# File 'lib/bytes_manip.rb', line 20 def bs_xor(bs1, bs2) fail unless bs1.bytesize == bs2.bytesize out = String.new(bs1) (0 .. bs1.bytesize - 1).each do |i| out.setbyte(i, bs1.getbyte(i) ^ bs2.getbyte(i)) end out end |
#desfire_crc(data) ⇒ Object
DESFire-specific CRC algorithm taking a byte string as input and returning a byte string of length 2 as output.
37 38 39 40 41 42 43 44 45 |
# File 'lib/bytes_manip.rb', line 37 def desfire_crc(data) wCRC = 0x6363 data.each_byte do |byte| byte = (byte ^ (wCRC & 0x00FF)) % 256 byte = (byte ^ (byte << 4)) % 256 wCRC = ((wCRC >> 8) ^ (byte << 8) ^ (byte << 3) ^ (byte >> 4)) % 65536 end [wCRC & 0xFF, (wCRC >> 8) & 0xFF].pack("C*") end |
#to_hex_array(array) ⇒ Object
Converts a byte array to an array holding strings representing the numbers in base 16. For debugging purposes.
15 16 17 |
# File 'lib/bytes_manip.rb', line 15 def to_hex_array(array) array.flatten.map { |e| e.to_s(16) } end |
#to_le_array(num, n) ⇒ Object
Converts a number to a little-endian array of n bytes.
5 6 7 8 9 10 11 |
# File 'lib/bytes_manip.rb', line 5 def to_le_array(num, n) out = Array.new(n) out.each_index do |i| out[i] = num % 256 num /= 256 end end |