passcard 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 564d68423c508f8bd705ec08e1dc0ffdd7ded2a4
4
+ data.tar.gz: 3d577da3416b5562f193d460e5fdedd1c9135633
5
+ SHA512:
6
+ metadata.gz: a9457809b27f11eb923e16b38463b235d7b20980b6056147e529513c2735b63d6f772a05eb265e4b27fbae30886551f631d17fa865ebbc54a3c8b8a41a6d0045
7
+ data.tar.gz: 32559a8cb8cfa2ca948ed6b435574cdf4fd9399857d6cc9873f92fc6200628b1f61ae01c5693eccee36e07f6b42e6353fc1091cdf033e3cb2721c1dcf0a5a138
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
13
+ coverage/
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --require spec_helper
2
+ --format documentation
3
+ --color
@@ -0,0 +1,5 @@
1
+ SimpleCov.start do
2
+ add_filter "/spec/"
3
+ add_group "Extensions", "lib/extensions"
4
+ add_group "Outputters", "lib/passcard/outputter"
5
+ end
@@ -0,0 +1,15 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.0
5
+
6
+ before_install: gem install bundler -v 1.15.4
7
+
8
+ deploy:
9
+ provider: rubygems
10
+ api_key:
11
+ secure: KTUGDjcaqzvT8MV3T2TVMekZTI7jm0dRW3RCgDyFJ3kgO9MBiceBbbCInc+RXJKeQHvnrnCnTZ0iEEB/+8lOhM47d3CEqTeOPq+OfL2mXQ5GsLFO8udxG353b4HonqicLhf94i//8Q9EzFniGWBGWr2qQcZUrcRPvQ5MgH25UtwAtdqXpjF/l/rtEoNt8f5YMagzUlQOs9419Zl/u+H29ghNLyIpGdvMqe7k177wlHRAKzGZ1qzL1FR2KTAg7kFDwQSUK8Gt5fYJheyaA/I13dgMpkJUCbaOm7WKvTTLtwKXBIL6aS3P8HHXo5zpVn+Sma5UAcQ7wfw5Z9C+Nqg9sAJUZ77yHKZAYkMcvaJRAhdGEDZ5Q8Y0ZFcvd3UmEu/17WQPy+w4BVqLmvWKlV9j4yCZnRJdlMol5wPsOGcJTgd0aI1dhJMbo4rN0jberg4FV8WKImSphxJ54sTyQkGbr7q+7eigebS+PEm+fBCS4MiTeDrA0gLgvsRGso447R3RlpBCnEdJAXyRL1ij6Gwfra1uhdlIgO4zJNjcofCg3/QQpazfUGrO6XjUYahHE/y7bCY84+1T6DX8oqNWvDJgYVlwBfTNO2E0GVD7EDrGHlM4At4H5Drxs+7mjvompWHYtJKCMBXZWAODySguW9rI1C+bsc+vnmloacF6cPegbdI=
12
+ gem: passcard
13
+ on:
14
+ tags: true
15
+ repo: nikhgupta/passcard
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at me@nikhgupta.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,9 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ gemspec
6
+
7
+ gem "nokogiri", :group => :test
8
+ gem 'simplecov', :require => false, :group => :test
9
+ gem "aruba", github: "cucumber/aruba", :group => [:test, :development]
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Nikhil Gupta
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,51 @@
1
+ # Passcard
2
+
3
+ ## TODO:
4
+
5
+ - [x] Run tests on Travis
6
+ - [ ] Update README
7
+ - [ ] Push to Rubygems
8
+
9
+ ## Welcome
10
+
11
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/passcard`. To experiment with that code, run `bin/console` for an interactive prompt.
12
+
13
+ TODO: Delete this and the text above, and describe your gem
14
+
15
+ ## Installation
16
+
17
+ Add this line to your application's Gemfile:
18
+
19
+ ```ruby
20
+ gem 'passcard'
21
+ ```
22
+
23
+ And then execute:
24
+
25
+ $ bundle
26
+
27
+ Or install it yourself as:
28
+
29
+ $ gem install passcard
30
+
31
+ ## Usage
32
+
33
+ TODO: Write usage instructions here
34
+
35
+ ## Development
36
+
37
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
38
+
39
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
40
+
41
+ ## Contributing
42
+
43
+ Bug reports and pull requests are welcome on GitHub at https://github.com/nikhgupta/passcard. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
44
+
45
+ ## License
46
+
47
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
48
+
49
+ ## Code of Conduct
50
+
51
+ Everyone interacting in the Passcard project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/nikhgupta/passcard/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "passcard"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ require "pry"
11
+ Pry.start
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ #
5
+ # This file was generated by Bundler.
6
+ #
7
+ # The application 'rspec' is installed as part of a gem, and
8
+ # this file is here to facilitate running it.
9
+ #
10
+
11
+ bundle_binstub = File.expand_path("../bundle", __FILE__)
12
+ load(bundle_binstub) if File.file?(bundle_binstub)
13
+
14
+ require "pathname"
15
+ ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
16
+ Pathname.new(__FILE__).realpath)
17
+
18
+ require "rubygems"
19
+ require "bundler/setup"
20
+
21
+ load Gem.bin_path("rspec-core", "rspec")
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "thor"
4
+ require "passcard"
5
+ require "passcard/cli"
6
+ require 'passcard/outputter/ascii_outputter'
7
+
8
+ pattern = Passcard.root.join("lib", "passcard", "outputter", "*.rb")
9
+ Dir.glob(pattern){|f| require "passcard/outputter/#{File.basename(f, '.rb')}"}
10
+
11
+ # version = "Passcard v#{Passcard::VERSION} - Generate password grids with ease."
12
+ begin
13
+ Passcard::CLI.start(ARGV)
14
+ rescue Passcard::Error => e
15
+ STDERR.puts "\x1b[31m[Passcard] Error: #{e.message}\x1b[0m"
16
+ exit 1
17
+ rescue StandardError => e
18
+ STDERR.puts "\x1b[31m[#{e.class}] FATAL: #{e.message}\x1b[0m"
19
+ STDERR.puts e.backtrace.join("\n ")
20
+ exit 2
21
+ end
@@ -0,0 +1,6 @@
1
+ require 'digest/sha2'
2
+ class String
3
+ def sha512
4
+ Digest::SHA512.hexdigest(self)
5
+ end
6
+ end
@@ -0,0 +1,69 @@
1
+ require "json"
2
+ require "base64"
3
+ require "openssl"
4
+ require "ostruct"
5
+
6
+ module Passcard
7
+ GRID_SIZE = [80, 80]
8
+ ALPHA_GRID = [40, 40]
9
+ NUMERIC_GRID = [20, 20]
10
+ CHARSET = '0123456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ@#$%&*<>?-+{}[]()\/'
11
+
12
+ class Error < StandardError; end
13
+
14
+ def self.root
15
+ Pathname.new(File.dirname(File.dirname(__FILE__)))
16
+ end
17
+
18
+ def self.outputters
19
+ @@outputters ||= {}
20
+ end
21
+
22
+ def self.register_outputter(name, klass, method_name)
23
+ @@outputters ||= {}
24
+ @@outputters[name.to_sym] = [klass, method_name.to_sym]
25
+ end
26
+
27
+ def self.unregister_outputter(name)
28
+ @@outputters.delete(name.to_sym)
29
+ end
30
+
31
+ def self.outputter_class_for(name)
32
+ klass = outputters[name.to_sym].first
33
+ return klass if klass.is_a?(Class)
34
+ Kernel.const_get(klass.to_s)
35
+ end
36
+
37
+ def self.encrypt!(key, object)
38
+ object = object.to_json
39
+ cipher = OpenSSL::Cipher.new('DES-EDE3-CBC').encrypt
40
+ cipher.key = Random.new(key.to_i(36)).bytes(24)
41
+ output = cipher.update(object) + cipher.final
42
+ Base64.encode64(output)
43
+ end
44
+
45
+ def self.decrypt!(key, enc_str)
46
+ cipher = OpenSSL::Cipher.new('DES-EDE3-CBC').decrypt
47
+ cipher.key = Random.new(key.to_i(36)).bytes(24)
48
+ decrypted = cipher.update(Base64.decode64(enc_str))
49
+ output = decrypted << cipher.final
50
+ JSON.parse(output)
51
+ end
52
+
53
+ def self.create!(*args)
54
+ Passcard::Generator.create_key_file(*args)
55
+ end
56
+
57
+ def self.read!(*args)
58
+ Passcard::Reader.read_key_file(*args)
59
+ end
60
+ end
61
+
62
+ Dir.glob(Passcard.root.join("lib", "extensions", "*.rb")){|f| require f}
63
+ require "passcard/version"
64
+ require "passcard/grid"
65
+ require "passcard/generator"
66
+ require "passcard/reader"
67
+ require "passcard/palette"
68
+ require "passcard/outputter"
69
+ require "passcard/outputter/ascii_outputter"
@@ -0,0 +1,50 @@
1
+ module Passcard
2
+ class CLI < Thor
3
+ def self.exit_on_failure?; true; end
4
+
5
+ desc "generate", "Generate a Passcard Key file."
6
+ method_option :identity_file, type: :string, aliases: "-i", default: "./passcard.key"
7
+ method_option :secret_key, type: :string, aliases: "-s"
8
+ method_option :charset, type: :string, aliases: "-c"
9
+ method_option :force, type: :boolean, aliases: "-f"
10
+ def generate
11
+ file = options[:identity_file]
12
+ if File.exist?(file) && !options[:force]
13
+ raise Passcard::Error, "Identity file exists!"
14
+ elsif File.exist?(file)
15
+ say_status "WARNING", "Overwriting file at: #{file}", :yellow
16
+ end
17
+
18
+ unless secret = options[:secret_key]
19
+ message = "Please, provide a secret key [Enter for none]:"
20
+ secret = ask(message).strip
21
+ puts
22
+ end
23
+
24
+ opts = options.except(:secret_key, :identity_file) || {}
25
+ Passcard.create!(secret, file, opts)
26
+ say_status "SUCCESS", "Created Passcard key in: #{file}"
27
+ end
28
+
29
+ desc "view IDENTITY_FILE", "View different grids stored in your Passcard Key file."
30
+ method_option :header, type: :boolean, default: true
31
+ method_option :color, type: :string, default: :passcard
32
+ method_option :type, type: :string, default: :card, aliases: "-t"
33
+ method_option :secret_key, type: :string, aliases: "-s"
34
+ method_option :format, type: :string, aliases: "-f", default: "ascii"
35
+ def view(identity_file)
36
+ unless secret = options[:secret_key]
37
+ message = "Please, provide your secret key [Enter for none]:"
38
+ secret = ask(message).strip
39
+ puts
40
+ end
41
+
42
+ data = Passcard.read!(secret, identity_file)
43
+ puts data.send("to_#{options[:format]}", options)
44
+ rescue OpenSSL::Cipher::CipherError
45
+ message = "Seems like you entered the wrong secret key,\n"
46
+ message += "or this does not seem to be a valid Passcard."
47
+ raise Passcard::Error, message
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,66 @@
1
+ module Passcard
2
+ class Generator
3
+ attr_accessor :options
4
+
5
+ def self.create_key_file(key, path, options = {})
6
+ passcard = self.new(key, options)
7
+ FileUtils.mkdir_p(File.dirname(path))
8
+ File.open(path, "w") do |f|
9
+ f.print "-" * 20 + " BEGIN PASSCARD KEY " + "-" * 23 + "\n"
10
+ f.print passcard.run
11
+ f.print "-" * 20 + " END PASSCARD KEY " + "-" * 25
12
+ end
13
+ end
14
+
15
+ def initialize(secret = nil, options = {})
16
+ @secret = secret.to_s.strip.sha512
17
+
18
+ @options = { "charset" => Passcard::CHARSET }.merge(options)
19
+ @options.merge!("size" => Passcard::GRID_SIZE,
20
+ "numeric" => Passcard::NUMERIC_GRID, "alpha" => Passcard::ALPHA_GRID)
21
+ end
22
+
23
+ def run
24
+ return encrypt_options! if options['grid']
25
+
26
+ charspace = options['charset'].chars.shuffle
27
+ numspace = options['charset'].gsub(/[^0-9]+/, '').chars.shuffle
28
+ alphaspace = options['charset'].gsub(/[^a-z0-9]+/i, '').chars.shuffle
29
+
30
+ numspace = (0..9).to_a.shuffle if numspace.empty?
31
+ alphaspace = (('a'..'z').to_a+('A'..'Z').to_a).shuffle if alphaspace.empty?
32
+
33
+ @options['grid'] = @options['size'][0].times.map do |r|
34
+ @options['size'][1].times.map do |c|
35
+ get_character(r, c, alphaspace, numspace, charspace)
36
+ end
37
+ end.join
38
+
39
+ encrypt_options!
40
+ end
41
+
42
+ def get_character(r, c, alphaspace, numspace, charspace)
43
+ space = alphanumeric?(r,c) ? alphaspace : charspace
44
+ space = numeric?(r,c) ? numspace : space
45
+ space.shuffle[(r + c) % space.length]
46
+ end
47
+
48
+ def numeric?(r, c)
49
+ return false if r >= @options["numeric"][0]
50
+ return false if c >= @options["numeric"][1]
51
+ return true
52
+ end
53
+
54
+ def alphanumeric?(r, c)
55
+ return false if r < @options["size"][0] - @options["alpha"][0]
56
+ return false if c < @options["size"][1] - @options["alpha"][1]
57
+ return true
58
+ end
59
+
60
+ protected
61
+
62
+ def encrypt_options!
63
+ Passcard.encrypt!(@secret, @options.to_h)
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,121 @@
1
+ require 'forwardable'
2
+
3
+ module Passcard
4
+ class Grid
5
+ extend Forwardable
6
+ def_delegators :to_str, :chars, :gsub
7
+ def_delegators :@arr, :take, :empty?, :first, :last
8
+
9
+ def initialize(arr)
10
+ @arr = arr
11
+ raise_if_invalid_array!
12
+ end
13
+
14
+ def ==(g2)
15
+ self.to_a == g2.to_a && g2.is_a?(self.class)
16
+ end
17
+
18
+ def [](*args)
19
+ self.rows_at(*args)
20
+ end
21
+
22
+ def row_size
23
+ @arr.size
24
+ end
25
+
26
+ def col_size
27
+ @arr.any? ? @arr[0].size : 0
28
+ end
29
+
30
+ def size
31
+ [row_size, col_size]
32
+ end
33
+
34
+ def length
35
+ row_size * col_size
36
+ end
37
+
38
+ def rows_at(*rows)
39
+ rows = rows.map{|a| a.respond_to?(:to_a) ? a.to_a : a}
40
+ self.class.new rows.flatten.map{|a| @arr[a % @arr.size]}
41
+ end
42
+
43
+ def cols_at(*cols)
44
+ cols = cols.map{|a| a.respond_to?(:to_a) ? a.to_a : a}
45
+ self.class.new @arr.map{|a| cols.flatten.map{|c| a[c % a.length]}}
46
+ end
47
+
48
+ def at(rows: [], cols: [])
49
+ return self if rows.empty? && cols.empty?
50
+ return self.rows_at(*rows) if cols.empty?
51
+ return self.cols_at(*cols) if rows.empty?
52
+ self.rows_at(*rows).cols_at(*cols)
53
+ end
54
+
55
+ def slice(coord1, coord2)
56
+ self.rows_at(coord1[0]...coord2[0]).cols_at(coord1[1]...coord2[1])
57
+ end
58
+
59
+ def transpose
60
+ self.class.new @arr.transpose
61
+ end
62
+
63
+ def numeric?
64
+ to_str =~ /\A[0-9]+\z/
65
+ end
66
+
67
+ def alphanumeric?
68
+ to_str =~ /\A[a-z0-9]+\z/i
69
+ end
70
+
71
+ def has_symbols?
72
+ return false if empty?
73
+ return false if alphanumeric?
74
+ (to_str.chars - ('!'..'~').to_a).empty?
75
+ end
76
+
77
+ # Returns new grid by rotating self so that the element at cnt in self is
78
+ # the first element of the new grid. If cnt is negative then it rotates in
79
+ # the opposite direction.
80
+ #
81
+ def rotate(r: 0, c: 0)
82
+ self.class.new @arr.rotate(r).map{|row| row.rotate(c)}
83
+ end
84
+
85
+ def to_a
86
+ @arr
87
+ end
88
+
89
+ def to_str
90
+ @arr.join
91
+ end
92
+
93
+ def to_vstr
94
+ transpose.to_str
95
+ end
96
+
97
+ def to_s
98
+ @arr.map{|x| x.join(" ")}.join("\n")
99
+ end
100
+
101
+ def print(*args)
102
+ options = args.last.is_a?(Hash) ? args.pop : {}
103
+ puts(col_size > 40 || options[:concise] ? to_s.gsub(" ", '') : to_s)
104
+ return self
105
+ end
106
+
107
+ def inspect
108
+ chars = to_str[0..36] + (length > 36 ? "...." : "")
109
+ chars = "" if length == 0
110
+ "#{self.class}[rows=#{row_size},cols=#{col_size},length=#{length}]{\"#{chars}\"}"
111
+ end
112
+
113
+
114
+ def raise_if_invalid_array!
115
+ valid = @arr.is_a?(Array)
116
+ valid &&= @arr.reject{|r| r.is_a?(Array)}.empty?
117
+ valid &&= @arr.join.length == @arr.size * (@arr[0].size rescue 0)
118
+ raise Passcard::Error, "A Grid requires 2D array" unless valid
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,88 @@
1
+ module Passcard
2
+ class Outputter
3
+ HEADERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 αβγδθλμπϕ $£¥€¢' + # 50
4
+ '! # % & * < = > ? @ ✓ ∞ ♬ ♡ ♢ ♤ ♧ ☯ ☾ ✈ ☎ ☀ ☁ ☂ ☃ ★ ⌘ ♞ ✂ ✎ ' # 30
5
+
6
+ attr_accessor :reader, :grid, :palette
7
+
8
+ def initialize(reader)
9
+ self.reader = reader
10
+ self.palette = Passcard::Palette.new
11
+ end
12
+
13
+ # Register one or more handler methods with this outputter.
14
+ # Passcard will then be able to use these methods to get the output
15
+ # from the outputter. For example, if you have an HtmlOutputter,
16
+ # you could do:
17
+ #
18
+ # register :to_html, :to_xml
19
+ #
20
+ # You could then do a Passcard.to_png and get the result of that method.
21
+ # The class which registers the method will receive the generator instance
22
+ # as the only argument, and the default implementation of initialize puts
23
+ # that into the +passcard+ accessor.
24
+ #
25
+ # You can also have different method names in the outputter by providing
26
+ # a hash:
27
+ #
28
+ # register to_html: :create_html, to_xml: :create_xml
29
+ #
30
+ def self.register(*args)
31
+ hash = args.last.is_a?(Hash) ? args.pop : {}
32
+ raise Passcard::Error, "You must register a method name!" if args.empty? && hash.empty?
33
+ args.each{|name| hash[name] = name}
34
+ hash.each do |name, method_name|
35
+ ::Passcard.register_outputter(name, self, method_name)
36
+ end
37
+ end
38
+
39
+ def use_palette(type, options = {})
40
+ options.merge!("n" => @grid.row_size) if @grid
41
+ self.palette.type = type
42
+ self.palette.options = options
43
+ end
44
+
45
+ def row_headers
46
+ headers = self.class.const_get("ROW_HEADERS") rescue nil
47
+ headers ||= self.class.const_get("HEADERS")
48
+ headers.gsub(/ /, '').chars.take(grid.row_size)
49
+ end
50
+
51
+ def col_headers
52
+ headers = self.class.const_get("COLUMN_HEADERS") rescue nil
53
+ headers ||= self.class.const_get("HEADERS")
54
+ headers.gsub(/ /, '').chars.take(grid.col_size)
55
+ end
56
+
57
+ def get_grid(options = {})
58
+ random = options[:type].to_s.to_sym == :random
59
+ coordinates = get_grid_coordinates(options)
60
+ @grid = reader.random_grid(20, 30) if random
61
+ @grid = reader.slice(*coordinates) if !random
62
+ use_palette :passcard
63
+ @grid
64
+ end
65
+
66
+ def data_in(file)
67
+ content = File.read(file)
68
+ regex = /^\s*__END__\s*$/
69
+ return "" if content.match(regex).nil?
70
+ content.split(regex).last.strip
71
+ end
72
+
73
+ private
74
+
75
+ def get_grid_coordinates(options = {})
76
+ case options[:type].to_s.to_sym
77
+ when :pincard then [[ 0, 0], [10,20]] # 10x20 numbers only
78
+ when :pincard_alt then [[10, 0], [20,20]] # 10x20 numbers only (alt)
79
+ when :alphanum then [[40,40], [66,66]] # 26x26 alphanumeric only
80
+ when :alphanum_alt then [[54,54], [80,80]] # 26x26 alphanumeric only (alt)
81
+ when :square then [[20,20], [40,40]] # 20x20 alphanum & symbols
82
+ when :card_large then [[ 0,20], [15,50]] # 15x30 alphanum & symbols
83
+ when :card then [[30,20], [40,40]] # 10x20 alphanum & symbols - card
84
+ else [[0,0], [80,80]]
85
+ end
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,37 @@
1
+ module Passcard
2
+ class AsciiOutputter < Outputter
3
+ register :to_ascii, to_s: :to_ascii
4
+
5
+ def to_ascii(options = {})
6
+ str = ""
7
+ get_grid(options)
8
+ use_palette options[:color]
9
+
10
+ str += get_col_headers if options[:header]
11
+
12
+ grid.row_size.times.map do |i|
13
+ str += row_headers[i].to_s + " | " if options[:header]
14
+ str += get_row(i, options[:color])
15
+ str += "\n"
16
+ end
17
+
18
+ str
19
+ end
20
+
21
+ private
22
+
23
+ def get_col_headers
24
+ " #{col_headers.join(" ")}\n #{"- "*col_headers.length}\n"
25
+ end
26
+
27
+ def get_row(idx, colors=true)
28
+ row = grid[idx].to_s
29
+ return row unless colors
30
+
31
+ str = "\x1b[48;2;#{@palette.colors[idx][:color].join(";")}m"
32
+ str += "\x1b[38;2;#{@palette.colors[idx][:text_color].join(";")}m"
33
+
34
+ "#{str}#{row}\x1b[0m"
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,127 @@
1
+ module Passcard
2
+ class HtmlOutputter < Outputter
3
+ register :to_html
4
+
5
+ def to_html(options = {})
6
+ html = ""
7
+ get_grid(options)
8
+ use_palette options[:color]
9
+
10
+ html += get_col_headers if options[:header]
11
+
12
+ grid.row_size.times.map do |i|
13
+ html += "<div class='row'>"
14
+ html += get_row_header(i) if options[:header]
15
+ html += get_row(i, options[:color])
16
+ html += "</div>"
17
+ end
18
+
19
+ data = data_in(__FILE__).gsub('{{GRID}}', html)
20
+ data = data.gsub('{{BACKGROUND}}', get_background) if options[:color]
21
+ data
22
+ end
23
+
24
+ private
25
+
26
+ def get_background
27
+ bg1= "rgb(#{@palette.colors[0][:color].join(",")})"
28
+ bg2= "rgb(#{@palette.colors[-1][:color].join(",")})"
29
+ "background:linear-gradient(#{bg2},#{bg1})"
30
+ end
31
+
32
+ def get_style(idx, colors = true)
33
+ return unless colors
34
+ color = "rgb(#{@palette.colors[idx][:color].join(",")})"
35
+ textc = "rgb(#{@palette.colors[idx][:text_color].join(",")})"
36
+ return "style='color: #{textc}; background: #{color}'"
37
+ end
38
+
39
+ def get_row(idx, colors=true)
40
+ <<-HTML
41
+ <div class='row-content' #{get_style(idx, colors)}>
42
+ <span>#{grid[idx].to_a.join("</span><span>")}</span>
43
+ </div>
44
+ HTML
45
+ end
46
+
47
+ def get_row_header(i)
48
+ <<-HTML
49
+ <div class='row-header'>
50
+ <span>#{row_headers[i]}</span>
51
+ </div>
52
+ HTML
53
+ end
54
+
55
+ def get_col_headers
56
+ <<-HTML
57
+ <div class='col-header'>
58
+ <span>#{col_headers.join("</span><span>")}</span>
59
+ </div>
60
+ HTML
61
+ end
62
+ end
63
+ end
64
+
65
+ __END__
66
+
67
+ <!DOCTYPE html>
68
+ <html>
69
+ <head>
70
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
71
+ <title> Passcard Grid </title>
72
+
73
+ <style type="text/css">
74
+ * {
75
+ margin: 0;
76
+ padding: 0;
77
+ font-family: monospace;
78
+ }
79
+ html, body {
80
+ height: 100%;
81
+ width: 100%;
82
+ color: white;
83
+ background-color: #666;
84
+ }
85
+ .passcard-grid {
86
+ width: 800px;
87
+ text-align: right;
88
+ }
89
+ span {
90
+ font-size: 17px;
91
+ padding: 4px;
92
+ height: 21px;
93
+ width: 21px;
94
+ text-align: center;
95
+ vertical-align: middle;
96
+ display: inline-block;
97
+ }
98
+ .row {
99
+ clear: both;
100
+ width: 800px;
101
+ text-align: right;
102
+ }
103
+ .row-header {
104
+ color: white;
105
+ background-color: #666;
106
+ }
107
+ .row-header span {
108
+ float: left;
109
+ }
110
+ .col-header {
111
+ padding-left: 28px
112
+ }
113
+ .col-header span, .row-header span {
114
+ font-weight: bold;
115
+ color: black;
116
+ }
117
+ .row-content {
118
+ margin-left: 40px;
119
+ }
120
+ </style>
121
+ </head>
122
+ <body style='{{BACKGROUND}}'>
123
+ <div class="passcard-grid">
124
+ {{GRID}}
125
+ </div>
126
+ </body>
127
+ </html>
@@ -0,0 +1,134 @@
1
+ module Passcard
2
+ class Palette
3
+ extend Forwardable
4
+ GOLDEN_RATIO = (1 + Math.sqrt(5))/2
5
+
6
+ attr_reader :type, :colors, :options
7
+ def_delegators :@colors, :count, :size, :take, :first, :last, :[]
8
+
9
+ def initialize(type = :passcard, options = {})
10
+ self.type = type
11
+ self.options = options
12
+ end
13
+
14
+ def type=(type)
15
+ @type = type.to_s.strip.empty? ? :passcard : type.to_sym
16
+
17
+ if !respond_to?("generate_colors_#{@type}", true)
18
+ raise Passcard::Error, "No such color generator: #{@type}"
19
+ end
20
+
21
+ update_colors
22
+ end
23
+
24
+ def options=(options = {})
25
+ @options = options
26
+ @options["n"] ||= (@options["size"][0] rescue 0)
27
+ update_colors
28
+ end
29
+
30
+ def update_colors
31
+ return unless type && options
32
+ @colors = send("generate_colors_#{type}", options).map do |rgb|
33
+ { color: rgb, text_color: readable_text_color_for(rgb) }
34
+ end
35
+ end
36
+
37
+ def list_types
38
+ self.methods.map do |method|
39
+ method.to_s.gsub!(/^generate_colors_/, '')
40
+ end.compact.map(&:to_sym)
41
+ end
42
+
43
+ protected
44
+
45
+ def generate_colors_martin_ankerl(options = {})
46
+ h = rand
47
+ s = options.fetch('s', 0.33)
48
+ v = options.fetch('v', 0.93)
49
+
50
+ options['n'].times.map do
51
+ h = (h + 1/GOLDEN_RATIO) % 1
52
+ hsv_to_rgb(h * 360, s, v)
53
+ end
54
+ end
55
+
56
+ def generate_colors_krazydad(options = {})
57
+ width = options.fetch('width', 55)
58
+ center = options.fetch('center', 200)
59
+ phase = options.fetch('phase', rand * Math::PI * 2.0)
60
+ freq = Math::PI / options['n'] * 2.0
61
+
62
+ options['n'].times.map do |i|
63
+ red = Math.sin(freq * i + 0 + phase) * width + center
64
+ green = Math.sin(freq * i + 2 + phase) * width + center
65
+ blue = Math.sin(freq * i + 4 + phase) * width + center
66
+ [red.round(0), green.round(0), blue.round(0)]
67
+ end
68
+ end
69
+
70
+ def generate_colors_gradient(options = {})
71
+ s = rand
72
+ v = options.fetch("v", 0.93)
73
+ from, to = generate_colors_martin_ankerl("s" => s, "v" => v, "n" => 2)
74
+
75
+ options['n'].times.map do |i|
76
+ m = i/options['n'].to_f
77
+ 3.times.map{ |j| (from[j]*m + to[j] * (1-m)).round(0) }
78
+ end
79
+ end
80
+
81
+ def generate_colors_passcard(options = {})
82
+ h = (360 * rand).round(2)
83
+ n = options['n']
84
+ smax = options.fetch('smax', 0.4)
85
+ n = n.times.map{|i| (1+i)/n.to_f * smax * 1.0}
86
+ n.flatten.map{|s| hsl_to_rgb(h, s, 1 - s)}
87
+ end
88
+
89
+ private
90
+
91
+ # For more info on conversions, read:
92
+ # https://en.wikipedia.org/wiki/HSL_and_HSV
93
+ #
94
+ # Hue is specified in range: 0 <= hue < 360
95
+ #
96
+ def hue_to_rgb(h, c, x, m)
97
+ y = [c, 0, x] if h < 360
98
+ y = [x, 0, c] if h < 300
99
+ y = [0, x, c] if h < 240
100
+ y = [0, c, x] if h < 180
101
+ y = [x, c, 0] if h < 120
102
+ y = [c, x, 0] if h < 60
103
+ y.map{ |a| ((a + m) * 255).round(0) }
104
+ end
105
+ def hsv_to_rgb(h, s, v)
106
+ c = v * s
107
+ x = c * (1 - ((h / 60.0) % 2 - 1).abs)
108
+ m = v - c
109
+ hue_to_rgb(h, c, x, m)
110
+ end
111
+ def hsl_to_rgb(h, s, l)
112
+ c = (1 - (2 * l - 1).abs) * s
113
+ x = c * (1 - ((h / 60.0) % 2 - 1).abs)
114
+ m = l - c / 2.0
115
+ hue_to_rgb(h, c, x, m)
116
+ end
117
+
118
+ # Read: https://www.w3.org/TR/WCAG20/#relativeluminancedef
119
+ def luminosity_for(rgb)
120
+ conv = rgb.map do |c|
121
+ c/255.0 <= 0.03928 ? c/255.0/12.92 : ((c/255.0+0.055)/1.055)**2.4
122
+ end
123
+ conv[0] * 0.2126 + conv[1] * 0.7152 + conv[2] * 0.0722
124
+ end
125
+
126
+ # Read: https://www.w3.org/TR/WCAG20/#contrast-ratiodef
127
+ def readable_text_color_for(rgb, dark = nil, light = nil)
128
+ dark ||= [ 0, 0, 0]
129
+ light ||= [255,255,255]
130
+ lc, ld, ll = [rgb, dark, light].map{|color| luminosity_for(color)}
131
+ (lc + 0.05) / (ld + 0.05) > (ll + 0.05) / (lc + 0.05) ? dark : light
132
+ end
133
+ end
134
+ end
@@ -0,0 +1,73 @@
1
+ require 'forwardable'
2
+
3
+ module Passcard
4
+ class Reader
5
+ extend Forwardable
6
+ def_delegators :to_hash, :[], :has_key?
7
+
8
+ def self.read_key_file(key, path)
9
+ data = File.readlines(path)
10
+ self.new(key, data[1...-1].join.strip)
11
+ end
12
+
13
+ attr_reader :opts, :grid
14
+
15
+ def initialize(key, enc_text)
16
+ secret, enc_text = key.sha512, enc_text
17
+ @opts = Passcard.decrypt!(secret, enc_text)
18
+ get_grid
19
+ end
20
+
21
+ def get_grid
22
+ return @grid if @grid
23
+ @grid = @opts.delete("grid")
24
+ @grid = @grid.chars.each_slice(@opts["size"][1]).to_a
25
+ @grid = Passcard::Grid.new(@grid)
26
+ end
27
+
28
+ def numeric_grid
29
+ @grid.slice([0, 0], @opts["numeric"])
30
+ end
31
+
32
+ def alpha_grid
33
+ ir = @opts["size"][0] - @opts["alpha"][0]
34
+ ic = @opts["size"][1] - @opts["alpha"][1]
35
+ @grid.slice([ir, ic], @opts["size"])
36
+ end
37
+
38
+ # Should be taken from all corners rather than the first:
39
+ def random_grid(rows = 10, cols = 10)
40
+ return Passcard::Grid.new([]) if rows * cols == 0
41
+ return @grid if rows * cols >= @grid.length
42
+
43
+ ir = rand(@opts["size"][0] - rows - 1).to_i
44
+ ic = rand(@opts["size"][1] - cols - 1).to_i
45
+ @grid.slice([ir, ic], [ir + rows, ic + cols])
46
+ end
47
+
48
+ def to_hash
49
+ @opts.merge("grid" => @grid.to_str)
50
+ end
51
+
52
+ def to_s(*a, &b)
53
+ return @grid.to_s unless Passcard.outputters.has_key?(:to_s)
54
+ klass, method = Passcard.outputters[:to_s]
55
+ klass.new(self).send(method, *a, &b) || @grid.to_s
56
+ end
57
+
58
+ def method_missing(m, *a, &b)
59
+ if Passcard.outputters.include?(m)
60
+ klass, method_name = Passcard.outputters[m]
61
+ klass.new(self).send(method_name, *a, &b)
62
+ elsif @grid.respond_to?(m)
63
+ @grid.send(m, *a, &b)
64
+ else
65
+ super
66
+ end
67
+ end
68
+
69
+ def respond_to?(*args)
70
+ @grid.respond_to?(*args) || super
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,3 @@
1
+ module Passcard
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,29 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "passcard/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "passcard"
8
+ spec.version = Passcard::VERSION
9
+ spec.authors = ["Nikhil Gupta"]
10
+ spec.email = ["me@nikhgupta.com"]
11
+
12
+ spec.summary = %q{Password Card Generator}
13
+ spec.description = %q{Password Card Generator}
14
+ spec.homepage = "https://github.com/nikhgupta/passcard"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_dependency "thor", "~> 0.20"
25
+ spec.add_development_dependency "pry", "~> 0.10"
26
+ spec.add_development_dependency "bundler", "~> 1.15"
27
+ spec.add_development_dependency "rake", "~> 10.0"
28
+ spec.add_development_dependency "rspec", "~> 3.0"
29
+ end
metadata ADDED
@@ -0,0 +1,140 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: passcard
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Nikhil Gupta
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-09-26 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: thor
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.20'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0.20'
27
+ - !ruby/object:Gem::Dependency
28
+ name: pry
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '0.10'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '0.10'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.15'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.15'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.0'
83
+ description: Password Card Generator
84
+ email:
85
+ - me@nikhgupta.com
86
+ executables:
87
+ - passcard
88
+ extensions: []
89
+ extra_rdoc_files: []
90
+ files:
91
+ - ".gitignore"
92
+ - ".rspec"
93
+ - ".simplecov"
94
+ - ".travis.yml"
95
+ - CODE_OF_CONDUCT.md
96
+ - Gemfile
97
+ - LICENSE.txt
98
+ - README.md
99
+ - Rakefile
100
+ - bin/console
101
+ - bin/rspec
102
+ - bin/setup
103
+ - exe/passcard
104
+ - lib/extensions/string.rb
105
+ - lib/passcard.rb
106
+ - lib/passcard/cli.rb
107
+ - lib/passcard/generator.rb
108
+ - lib/passcard/grid.rb
109
+ - lib/passcard/outputter.rb
110
+ - lib/passcard/outputter/ascii_outputter.rb
111
+ - lib/passcard/outputter/html_outputter.rb
112
+ - lib/passcard/palette.rb
113
+ - lib/passcard/reader.rb
114
+ - lib/passcard/version.rb
115
+ - passcard.gemspec
116
+ homepage: https://github.com/nikhgupta/passcard
117
+ licenses:
118
+ - MIT
119
+ metadata: {}
120
+ post_install_message:
121
+ rdoc_options: []
122
+ require_paths:
123
+ - lib
124
+ required_ruby_version: !ruby/object:Gem::Requirement
125
+ requirements:
126
+ - - ">="
127
+ - !ruby/object:Gem::Version
128
+ version: '0'
129
+ required_rubygems_version: !ruby/object:Gem::Requirement
130
+ requirements:
131
+ - - ">="
132
+ - !ruby/object:Gem::Version
133
+ version: '0'
134
+ requirements: []
135
+ rubyforge_project:
136
+ rubygems_version: 2.6.10
137
+ signing_key:
138
+ specification_version: 4
139
+ summary: Password Card Generator
140
+ test_files: []