Created
July 1, 2013 17:20
-
-
Save namxam/5902768 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'smartcard' | |
#UID_CMD = "\xFF\xCA\x00\x00\x00" | |
UID_CMD = "\xFF\xCA\x00\x00\x00" | |
def format_readable(sequence) | |
sequence.to_s.unpack('C*').join | |
end | |
stop = false | |
until stop | |
begin | |
context = Smartcard::PCSC::Context.new | |
if context.valid? | |
readers = context.readers | |
if readers.empty? | |
puts 'Please attach an PC/SC compliant smart card reader!' | |
exit | |
else | |
queries = Smartcard::PCSC::ReaderStateQueries.new readers.length | |
readers.each_with_index do |name, index| | |
queries[index].reader_name = name | |
queries[index].current_state = :unknown | |
end | |
# Initial state is "unknown" | |
puts | |
puts '+' + '-' * 78 + '+' | |
puts "| Please insert smart-card card in reader #{@reader_name}" | |
puts '+' + '-' * 78 + '+' | |
until queries[0].current_state.include?(:present) do | |
context.wait_for_status_change(queries) | |
queries.ack_changes | |
end | |
puts | |
puts " * Card detected" | |
if card = Smartcard::PCSC::Card.new(context, readers[0]) | |
response = card.transmit(UID_CMD) | |
puts " * Response length: #{response.size}\n" | |
print " * Status: #{format_readable(response[-2,2])} " | |
case response[-2,2] | |
when "\x90\x00" | |
print "Success" | |
puts " Card ID: #{format_readable(response[0,4])}\n" | |
when "\x00\x00" | |
puts "No data" | |
when "\x67\x00" | |
puts "Bad APU" | |
when "\x6A\x82" | |
puts "Le is greater" | |
when "\x6CP1" | |
puts "Le is shorter" | |
else | |
puts "failure" | |
end | |
card.disconnect | |
# Wait until the card has been removed before checking for a new one | |
until queries[0].current_state.include?(:empty) do | |
context.wait_for_status_change(queries) | |
queries.ack_changes | |
end | |
end | |
end | |
end | |
rescue Smartcard::PCSC::Exception => ex | |
puts ex.message | |
ensure | |
# Disconnect | |
context.release | |
end | |
Signal.trap('INT') { stop = true } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment