Using the ruby-nfc gem

Installation

gem install ruby-nfc

observed:

Fetching: ruby-nfc-1.3.gem (100%)
        Don't forget to install libnfc and libfreefare
        see installation instructions here: 
        https://github.com/hexdigest/ruby-nfc
Successfully installed ruby-nfc-1.3
Parsing documentation for ruby-nfc-1.3
Installing ri documentation for ruby-nfc-1.3
Done installing documentation for ruby-nfc after 4 seconds
1 gem installed

We 1st need to install openssl, as it contains the libcrypto file which is used by libfreefare.

sudo apt-get install openssl

Then we download and compile libfreefare.

git clone https://code.google.com/p/libfreefare/
cd libfreefare
autoreconf -vis
sudo ./configure  make  make install

The ruby-nfc gem requires the file /usr/local/lib/libfreefare.so and with my setup I had to manually link to it e.g.

ln -s /home/james/libfreefare/libfreefare/.libs/libfreefare.so /usr/local/lib/libfreefare.so

Running the example code

You need superuser permission to access the NFC module which is why I opened an IRB session using root.

Copy and paste in the following code:

require 'ruby-nfc'

puts Library version: #{NFC.version}
readers = NFC::Reader.all
puts Available readers: #{readers}

# The order of tag types in poll arguments defines priority of tag types
readers[0].poll(Mifare::Classic::Tag) do |tag|
  begin
    puts Applied #{tag.class.name}: #{tag}

    if tag.is_a? Mifare::Classic::Tag then
      if tag.auth(4, :key_a, FFFFFFFFFFFF)
        # Mifare::Classic::Tag.read method reads contents of last authenticated
        # block
        puts Contents of block 0x04: #{tag.read.unpack('H*').pop}
      else
        puts Authentication failed!
      end
    end
  rescue Exception = e
    p e
  end
end

Output

Applied Mifare::Classic::Tag: 9d424e7c Mifare Classic 1k SAK: 0x8
Contents of block 0x04: 25a65be2a654c7b80937e2dafd6ec686
Applied Mifare::Classic::Tag: a5334611 Mifare Classic 1k SAK: 0x8
Contents of block 0x04: 00000000000000000000000000000000
Applied Mifare::Classic::Tag: 9d424e7c Mifare Classic 1k SAK: 0x8
Contents of block 0x04: 25a65be2a654c7b80937e2dafd6ec686

In the above output you can seen I swiped the RFID card, then the RFID keyfob, and then the card again.

Resources