#!/usr/bin/env ruby # # License: BSD # # Copyright (c) 2006-2007, Gregory Fleischer (gfleischer@gmail.com) # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # 3. The names of the authors may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # require 'getoptlong' opts = GetoptLong.new( ['--help', '-h', GetoptLong::NO_ARGUMENT], ['--key', '-k', GetoptLong::REQUIRED_ARGUMENT], ['--encrypt', '-e', GetoptLong::OPTIONAL_ARGUMENT], ['--decrypt', '-d', GetoptLong::OPTIONAL_ARGUMENT] ) def usage puts "usage: #{$0} --key --encrypt|--decrypt" end encrypt=false decrypt=false key=nil text=nil opts.each do |opt,arg| case opt when '--help' usage() exit 0 when '--key' key = arg.dup() when '--encrypt' text = arg.dup() encrypt = true when '--decrypt' text = arg.dup() decrypt = true end end if key.nil? puts "missing key" usage() exit 1 end if not encrypt and not decrypt puts "must specify either encrypt or decrypt" usage() exit 1 end unless key.match(/^[A-Za-z]+$/) puts "invalid key" usage() exit 1 end if text.nil? || 0 == text.length text = STDIN.read() end text.gsub!(/[^a-zA-Z]/) {|c|} if key.match(/^[a-z]+$/) text.downcase! unless text.nil? alpha = ('a'..'z').to_a offset = 'a'[0] elsif key.match(/^[A-Z]+$/) text.upcase! unless text.nil? alpha = ('A'..'Z').to_a offset = 'A'[0] else puts "invalid key #{key}" exit 1 end keylen = key.length i=0 text.each_byte do |c| k = key[i % keylen] - offset c -= offset if encrypt print alpha[(c + k) % 26] else print alpha[(c - k) % 26] end i += 1 end puts "" # eof