4 This file is part of the AVR-Crypto-Lib.
5 Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de)
7 This program is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>.
25 $buffer_size = 0 # set automatically in init_system
26 $conffile_check = Hash.new
27 $conffile_check.default = 0
31 ################################################################################
33 ################################################################################
35 def read_line_from_device()
36 repeat_counter = 10000
42 end while !l && repeat_counter > 0
44 $logfile.printf("DBG: (%02d:%02d:%02d)<< %s\n", t.hour, t.min, t.sec, l.inspect) if $debug
45 if l && l.include?("AVR-Crypto-Lib")
46 $logfile.printf("DBG: system crashed !!!\n")
52 def readconfigfile(fname, conf)
53 return conf if $conffile_check[fname]==1
54 $conffile_check[fname]=1
56 if not File.exists?(fname)
59 file = File.open(fname, "r")
62 next if /[\s]*#/.match(line)
63 if m=/\[[\s]*([^\s]*)[\s]*\]/.match(line)
68 next if ! /=/.match(line)
69 m=/[\s]*([^\s]*)[\s]*=[\s]*([^\s]*)/.match(line)
71 Dir.glob(m[2]){ |fn| conf = readconfigfile(fn, conf) }
73 conf[section][m[1]] = m[2]
80 ################################################################################
82 ################################################################################
89 $sp.print("echo off\r")
98 x = l.split.collect { |e| e.to_i(16) }
100 end while x.length == 16
104 def goto_next_header(f)
106 m = /^#\ (=|-)*[=-]{5}/.match(l)
107 t = :subblock if m && m[1] == '-'
108 t = :mainblock if m && m[1] == '='
109 if !m && n = /^#\ (.*)$/.match(l)
121 def skip_file_header(f)
123 return if m = /^#\ [=]{40}/.match(l)
130 a,b = goto_next_header(f)
136 printf(">>%sblock: %s\n", a==:mainblock ? "main":"sub", b)
139 printf(">item: %s\n", b)
141 printf(">length: %d (0x%x)\n>data:", d.length, d.length)
144 printf("\n>") if i % 16 == 0
152 >item: RSA modulus n:
153 >item: RSA public exponent e:
154 >item: RSA private exponent d:
157 >item: p's CRT exponent dP:
158 >item: q's CRT exponent dQ:
159 >item: CRT coefficient qInv:
165 q,id = goto_next_header(f)
167 m = /[\ \t]([^\ \t]*):[\ \t]*$/.match(id)
173 req_items = ['n', 'e', 'd', 'p', 'q', 'dP', 'dQ', 'qInv']
174 req_items.each do |e|
175 printf("ERROR: key component %s is missing!\n", e) if !h[e]
178 printf("ERROR: unknown item '%s'!\n", e) if !req_items.index(e)
184 >item: Message to be encrypted:
191 'Message to be encrypted:' => 'msg',
193 'Encryption:' => 'enc'}
196 q,id = goto_next_header(f)
199 printf("ERROR: unknown item '%s'!\n", id) if !n
202 req_items = ['msg', 'seed', 'enc']
203 req_items.each do |e|
204 printf("ERROR: testvector component %s is missing!\n", e) if !h[e]
206 while h['enc'][0] == 0
207 h['enc'].delete_at(0)
215 end while !s || !s.include?('.')
219 $sp.printf("%d\r", d.length)
220 while l = read_line_from_device()
221 break if /data:/.match(l)
223 printf "ERROR: got no answer from system!" if !l
226 $sp.printf("%02x", e)
229 # we should now wait for incomming dot
239 printf("\n\t") if i % 16 == 0
243 puts('') if i % 16 != 1
250 s += "\n\t" if i % 16 == 0
251 s += sprintf('%02x ', e)
254 s += "\n" if i % 16 != 1
259 $sp.print("load-key\r")
261 v = ['n', 'e', 'p', 'q', 'dP', 'dQ', 'qInv']
264 $logfile.printf("DBG: loaded %s\n", e) if $debug
266 while l = read_line_from_device()
267 break if />/.match(l)
273 $sp.print("seed-test\r")
275 load_bigint(tv['msg'])
276 $logfile.printf("DBG: loaded %s\n", 'msg') if $debug
278 tv['seed'].each { |e| $sp.printf(" %02x", e) }
279 while l = read_line_from_device()
280 break if /ciphertext:/.match(l)
284 l = read_line_from_device()
285 break if ! /([0-9A-Fa-f]{2}\s*)+/.match(l)
288 test_enc_a = Array.new
289 test_enc = test_enc.split(/[\W\r\n]+/)
291 v = e.sub(/[^0-9A-Fa-f]/, '')
292 test_enc_a << v if v.length == 2
294 test_enc_a.collect!{ |e| e.to_i(16) }
295 enc_ok = (test_enc_a == tv['enc'])
297 $logfile.printf("DBG: ref = %s test = %s\n", str_hexdump(tv['enc']) , str_hexdump(test_enc_a))
301 l = read_line_from_device()
302 m = /(>>OK<<|ERROR)/.match(l)
305 return true if enc_ok && (m[1] == '>>OK<<')
309 def run_test(f,skip_key=1,skip_vec=1)
316 a,b = goto_next_header(f)
317 $logfile.printf("DBG: a=%s b=%s\n", a.inspect, b.inspect) if $debug
320 # Example 1: A 1024-bit RSA Key Pair
321 b.sub!(/[\d]+:/) { |s| sprintf("%3d,", s.to_i)}
322 printf("\n>> %s: ", b)
323 # (35-b.length).times { putc(' ')}
326 if b == 'Components of the RSA Key Pair'
330 load_key(k) if skip_key <= key_idx
334 if (key_idx > skip_key) || (key_idx == skip_key && vec_idx >= skip_vec)
351 ########################################
353 ########################################
356 opts = Getopt::Std.getopts("dc:f:il:s:n:")
359 conf = readconfigfile("/etc/testport.conf", conf)
360 conf = readconfigfile("~/.testport.conf", conf)
361 conf = readconfigfile("testport.conf", conf)
362 conf = readconfigfile(opts["c"], conf) if opts["c"]
366 puts("serial port interface version: " + SerialPort::VERSION);
368 params = { "baud" => conf["PORT"]["baud"].to_i,
369 "data_bits" => conf["PORT"]["databits"].to_i,
370 "stop_bits" => conf["PORT"]["stopbits"].to_i,
371 "parity" => SerialPort::NONE }
372 params["paraty"] = SerialPort::ODD if conf["PORT"]["paraty"].downcase == "odd"
373 params["paraty"] = SerialPort::EVEN if conf["PORT"]["paraty"].downcase == "even"
374 params["paraty"] = SerialPort::MARK if conf["PORT"]["paraty"].downcase == "mark"
375 params["paraty"] = SerialPort::SPACE if conf["PORT"]["paraty"].downcase == "space"
377 puts("\nPort: "+conf["PORT"]["port"]+"@" +
378 params["baud"].to_s +
380 params["data_bits"].to_s +
381 conf["PORT"]["paraty"][0,1].upcase +
382 params["stop_bits"].to_s +
385 $sp = SerialPort.new(conf["PORT"]["port"], params)
387 $sp.read_timeout=1000; # 5 minutes
388 $sp.flow_control = SerialPort::SOFT
390 $debug = true if opts['d']
392 if opts['s'] && m = opts['s'].match(/([\d]+\.([\d]+))/)
400 if opts['l'] && ! opts['n']
401 $logfile = File.open(opts['l'], 'w')
404 base_name = 'rsaes_oaep'
407 logfilename = conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '.txt'
408 if File.exists?(logfilename)
411 logfilename = sprintf('%s%04d%s', conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '_', i, '.txt')
413 end while(File.exists?(logfilename))
415 n1 = sprintf('%s%04d%s', conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '_', i-2, '.txt')
416 n2 = sprintf('%s%04d%s', conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '_', i-1, '.txt')
418 printf("%s -> %s\n", n1, n2)
421 n1 = sprintf('%s%s', conf['PORT']['testlogbase'], base_name + '_' + opts['n'] + '.txt')
422 n2 = sprintf('%s%04d%s', conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '_', 1, '.txt')
424 printf("%s -> %s\n", n1, n2)
425 logfilename = conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '.txt'
427 printf("logging to %s", logfilename)
428 $logfile = File.open(logfilename, 'w')
432 $logfile = STDOUT if ! $logfile
436 f = File.open(opts['f'], "r")
438 ok,fail = run_test(f,sk,sv)
439 printf("\nOK: %d FAIL: %d :-%s\n",ok,fail, fail==0 ? ')':'(')