lib_string_encryption 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 Jason Rogers
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,32 @@
1
+ = lib_string_encryption
2
+
3
+ A library that allows for super simple string encryption.
4
+
5
+ == Examples
6
+ Description:
7
+ Outputs a random string for encryption that is 28 characters long.
8
+
9
+ rake print_key
10
+
11
+ == Usage
12
+ Encryption:
13
+ "Test".encrypt
14
+ => "NDFkZTc5NDEyNTg1MzdiZPzBrxZz5aoN%0A"
15
+
16
+ Decryption:
17
+ "NDFkZTc5NDEyNTg1MzdiZPzBrxZz5aoN%0A".decrypt
18
+ => "Test"
19
+
20
+ == Note on Patches/Pull Requests
21
+
22
+ * Fork the project.
23
+ * Make your feature addition or bug fix.
24
+ * Add tests for it. This is important so I don't break it in a
25
+ future version unintentionally.
26
+ * Commit, do not mess with rakefile, version, or history.
27
+ (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
28
+ * Send me a pull request. Bonus points for topic branches.
29
+
30
+ == Copyright
31
+
32
+ Copyright (c) 2010 Jason Rogers. See LICENSE for details.
data/Rakefile ADDED
@@ -0,0 +1,58 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ begin
5
+ require 'jeweler'
6
+ Jeweler::Tasks.new do |gem|
7
+ gem.name = "lib_string_encryption"
8
+ gem.summary = %Q{A library that allows for super simple string encryption}
9
+ gem.description = %Q{String Encryption library}
10
+ gem.email = "jacaetevha@gmail.com"
11
+ gem.homepage = "http://github.com/jacaetevha/lib_string_encryption"
12
+ gem.authors = ["Jason Rogers"]
13
+ gem.add_development_dependency "rspec", ">= 1.2.9"
14
+ gem.add_development_dependency "yard", ">= 0"
15
+ # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
16
+ end
17
+ Jeweler::GemcutterTasks.new
18
+ rescue LoadError
19
+ puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
20
+ end
21
+
22
+ require 'spec/rake/spectask'
23
+ Spec::Rake::SpecTask.new(:spec) do |spec|
24
+ spec.libs << 'lib' << 'spec'
25
+ spec.spec_files = FileList['spec/**/*_spec.rb']
26
+ end
27
+
28
+ Spec::Rake::SpecTask.new(:rcov) do |spec|
29
+ spec.libs << 'lib' << 'spec'
30
+ spec.pattern = 'spec/**/*_spec.rb'
31
+ spec.rcov = true
32
+ end
33
+
34
+ task :spec => :check_dependencies
35
+
36
+ task :default => :spec
37
+
38
+ begin
39
+ require 'yard'
40
+ YARD::Rake::YardocTask.new
41
+ rescue LoadError
42
+ task :yardoc do
43
+ abort "YARD is not available. In order to run yardoc, you must: sudo gem install yard"
44
+ end
45
+ end
46
+
47
+ desc "Produces a constant for string encryption and sets it in ENV['LIB_STRING_ENCRYPTION_KEY']"
48
+ task :key do
49
+ $:.unshift 'lib'
50
+ require 'lib_string_encryption'
51
+ key = StringEncryption::SecureRandom.hex(14)
52
+ ENV['LIB_STRING_ENCRYPTION_KEY'] = key
53
+ key
54
+ end
55
+
56
+ task :print_key => :key do
57
+ puts ENV['LIB_STRING_ENCRYPTION_KEY']
58
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.0
@@ -0,0 +1,4 @@
1
+ $:.unshift File.dirname(__FILE__)
2
+ require "string_encryption/secure_random"
3
+ require "string_encryption/core_ext"
4
+ require "string_encryption/encryption"
@@ -0,0 +1,9 @@
1
+ String.class_eval do
2
+ def encrypt
3
+ StringEncryption.encrypt(self)
4
+ end
5
+
6
+ def decrypt
7
+ StringEncryption.decrypt(self)
8
+ end
9
+ end
@@ -0,0 +1,29 @@
1
+ require 'base64'
2
+ require 'uri'
3
+
4
+ module StringEncryption
5
+ def self.decrypt(encrypted_data)
6
+ des = OpenSSL::Cipher::Cipher.new("des-ede3-cbc")
7
+ des.decrypt
8
+ des.key = ENV['LIB_STRING_ENCRYPTION_KEY']
9
+ encrypted_data = URI.unescape(encrypted_data)
10
+ encrypted_data = Base64.decode64(encrypted_data)
11
+
12
+ des.iv = encrypted_data.slice!(0,8)
13
+
14
+ des.update(encrypted_data) + des.final
15
+ end
16
+
17
+ def self.encrypt(string)
18
+ des = OpenSSL::Cipher::Cipher.new("des-ede3-cbc")
19
+ des.encrypt
20
+ des.key = ENV['LIB_STRING_ENCRYPTION_KEY']
21
+
22
+ des.iv = iv = SecureRandom.hex(4)
23
+
24
+ data = des.update(string) + des.final
25
+ data = iv + data
26
+ data = Base64.encode64(data)
27
+ data = URI.escape(data, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
28
+ end
29
+ end
@@ -0,0 +1,198 @@
1
+ begin
2
+ require 'securerandom'
3
+ rescue LoadError
4
+ end
5
+
6
+ module StringEncryption
7
+ if defined?(::SecureRandom)
8
+ # Use Ruby's SecureRandom library if available.
9
+ SecureRandom = ::SecureRandom # :nodoc:
10
+ else
11
+ # = Secure random number generator interface.
12
+ #
13
+ # This library is an interface for secure random number generator which is
14
+ # suitable for generating session key in HTTP cookies, etc.
15
+ #
16
+ # It supports following secure random number generators.
17
+ #
18
+ # * openssl
19
+ # * /dev/urandom
20
+ # * Win32
21
+ #
22
+ # *Note*: This module was taken directly from ActiveSupport, which is based.
23
+ # on SecureRandom from Ruby 1.9
24
+ #
25
+ # == Example
26
+ #
27
+ # # random hexadecimal string.
28
+ # p SecureRandom.hex(10) #=> "52750b30ffbc7de3b362"
29
+ # p SecureRandom.hex(10) #=> "92b15d6c8dc4beb5f559"
30
+ # p SecureRandom.hex(11) #=> "6aca1b5c58e4863e6b81b8"
31
+ # p SecureRandom.hex(12) #=> "94b2fff3e7fd9b9c391a2306"
32
+ # p SecureRandom.hex(13) #=> "39b290146bea6ce975c37cfc23"
33
+ # ...
34
+ #
35
+ # # random base64 string.
36
+ # p SecureRandom.base64(10) #=> "EcmTPZwWRAozdA=="
37
+ # p SecureRandom.base64(10) #=> "9b0nsevdwNuM/w=="
38
+ # p SecureRandom.base64(10) #=> "KO1nIU+p9DKxGg=="
39
+ # p SecureRandom.base64(11) #=> "l7XEiFja+8EKEtY="
40
+ # p SecureRandom.base64(12) #=> "7kJSM/MzBJI+75j8"
41
+ # p SecureRandom.base64(13) #=> "vKLJ0tXBHqQOuIcSIg=="
42
+ # ...
43
+ #
44
+ # # random binary string.
45
+ # p SecureRandom.random_bytes(10) #=> "\016\t{\370g\310pbr\301"
46
+ # p SecureRandom.random_bytes(10) #=> "\323U\030TO\234\357\020\a\337"
47
+ # ...
48
+ module SecureRandom
49
+ # SecureRandom.random_bytes generates a random binary string.
50
+ #
51
+ # The argument n specifies the length of the result string.
52
+ #
53
+ # If n is not specified, 16 is assumed.
54
+ # It may be larger in future.
55
+ #
56
+ # If secure random number generator is not available,
57
+ # NotImplementedError is raised.
58
+ def self.random_bytes(n=nil)
59
+ n ||= 16
60
+
61
+ unless defined? OpenSSL
62
+ begin
63
+ require 'openssl'
64
+ rescue LoadError
65
+ end
66
+ end
67
+
68
+ if defined? OpenSSL::Random
69
+ return OpenSSL::Random.random_bytes(n)
70
+ end
71
+
72
+ if !defined?(@has_urandom) || @has_urandom
73
+ flags = File::RDONLY
74
+ flags |= File::NONBLOCK if defined? File::NONBLOCK
75
+ flags |= File::NOCTTY if defined? File::NOCTTY
76
+ flags |= File::NOFOLLOW if defined? File::NOFOLLOW
77
+ begin
78
+ File.open("/dev/urandom", flags) {|f|
79
+ unless f.stat.chardev?
80
+ raise Errno::ENOENT
81
+ end
82
+ @has_urandom = true
83
+ ret = f.readpartial(n)
84
+ if ret.length != n
85
+ raise NotImplementedError, "Unexpected partial read from random device"
86
+ end
87
+ return ret
88
+ }
89
+ rescue Errno::ENOENT
90
+ @has_urandom = false
91
+ end
92
+ end
93
+
94
+ if !defined?(@has_win32)
95
+ begin
96
+ require 'Win32API'
97
+
98
+ crypt_acquire_context = Win32API.new("advapi32", "CryptAcquireContext", 'PPPII', 'L')
99
+ @crypt_gen_random = Win32API.new("advapi32", "CryptGenRandom", 'LIP', 'L')
100
+
101
+ hProvStr = " " * 4
102
+ prov_rsa_full = 1
103
+ crypt_verifycontext = 0xF0000000
104
+
105
+ if crypt_acquire_context.call(hProvStr, nil, nil, prov_rsa_full, crypt_verifycontext) == 0
106
+ raise SystemCallError, "CryptAcquireContext failed: #{lastWin32ErrorMessage}"
107
+ end
108
+ @hProv, = hProvStr.unpack('L')
109
+
110
+ @has_win32 = true
111
+ rescue LoadError
112
+ @has_win32 = false
113
+ end
114
+ end
115
+ if @has_win32
116
+ bytes = " " * n
117
+ if @crypt_gen_random.call(@hProv, bytes.size, bytes) == 0
118
+ raise SystemCallError, "CryptGenRandom failed: #{lastWin32ErrorMessage}"
119
+ end
120
+ return bytes
121
+ end
122
+
123
+ raise NotImplementedError, "No random device"
124
+ end
125
+
126
+ # SecureRandom.hex generates a random hex string.
127
+ #
128
+ # The argument n specifies the length of the random length.
129
+ # The length of the result string is twice of n.
130
+ #
131
+ # If n is not specified, 16 is assumed.
132
+ # It may be larger in future.
133
+ #
134
+ # If secure random number generator is not available,
135
+ # NotImplementedError is raised.
136
+ def self.hex(n=nil)
137
+ random_bytes(n).unpack("H*")[0]
138
+ end
139
+
140
+ # SecureRandom.base64 generates a random base64 string.
141
+ #
142
+ # The argument n specifies the length of the random length.
143
+ # The length of the result string is about 4/3 of n.
144
+ #
145
+ # If n is not specified, 16 is assumed.
146
+ # It may be larger in future.
147
+ #
148
+ # If secure random number generator is not available,
149
+ # NotImplementedError is raised.
150
+ def self.base64(n=nil)
151
+ [random_bytes(n)].pack("m*").delete("\n")
152
+ end
153
+
154
+ # SecureRandom.random_number generates a random number.
155
+ #
156
+ # If an positive integer is given as n,
157
+ # SecureRandom.random_number returns an integer:
158
+ # 0 <= SecureRandom.random_number(n) < n.
159
+ #
160
+ # If 0 is given or an argument is not given,
161
+ # SecureRandom.random_number returns an float:
162
+ # 0.0 <= SecureRandom.random_number() < 1.0.
163
+ def self.random_number(n=0)
164
+ if 0 < n
165
+ hex = n.to_s(16)
166
+ hex = '0' + hex if (hex.length & 1) == 1
167
+ bin = [hex].pack("H*")
168
+ mask = bin[0]
169
+ mask |= mask >> 1
170
+ mask |= mask >> 2
171
+ mask |= mask >> 4
172
+ begin
173
+ rnd = SecureRandom.random_bytes(bin.length)
174
+ rnd[0] = rnd[0] & mask
175
+ end until rnd < bin
176
+ rnd.unpack("H*")[0].hex
177
+ else
178
+ # assumption: Float::MANT_DIG <= 64
179
+ i64 = SecureRandom.random_bytes(8).unpack("Q")[0]
180
+ Math.ldexp(i64 >> (64-Float::MANT_DIG), -Float::MANT_DIG)
181
+ end
182
+ end
183
+
184
+ # Following code is based on David Garamond's GUID library for Ruby.
185
+ def self.lastWin32ErrorMessage # :nodoc:
186
+ get_last_error = Win32API.new("kernel32", "GetLastError", '', 'L')
187
+ format_message = Win32API.new("kernel32", "FormatMessageA", 'LPLLPLPPPPPPPP', 'L')
188
+ format_message_ignore_inserts = 0x00000200
189
+ format_message_from_system = 0x00001000
190
+
191
+ code = get_last_error.call
192
+ msg = "\0" * 1024
193
+ len = format_message.call(format_message_ignore_inserts + format_message_from_system, 0, code, 0, msg, 1024, nil, nil, nil, nil, nil, nil, nil, nil)
194
+ msg[0, len].tr("\r", '').chomp
195
+ end
196
+ end
197
+ end
198
+ end
@@ -0,0 +1,11 @@
1
+ require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
2
+
3
+ describe 'String Encryption' do
4
+ it "should encrypt strings" do
5
+ "Hello World".should_not == "Hello World".encrypt
6
+ end
7
+
8
+ it "should decrypt a string that's been encrypted" do
9
+ "Hello World".encrypt.decrypt.should == "Hello World"
10
+ end
11
+ end
data/spec/spec.opts ADDED
@@ -0,0 +1 @@
1
+ --color
@@ -0,0 +1,11 @@
1
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
2
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
3
+ require 'lib_string_encryption'
4
+ require 'spec'
5
+ require 'spec/autorun'
6
+
7
+ ENV['LIB_STRING_ENCRYPTION_KEY'] = StringEncryption::SecureRandom.hex(14)
8
+
9
+ Spec::Runner.configure do |config|
10
+
11
+ end
metadata ADDED
@@ -0,0 +1,99 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: lib_string_encryption
3
+ version: !ruby/object:Gem::Version
4
+ prerelease: false
5
+ segments:
6
+ - 0
7
+ - 1
8
+ - 0
9
+ version: 0.1.0
10
+ platform: ruby
11
+ authors:
12
+ - Jason Rogers
13
+ autorequire:
14
+ bindir: bin
15
+ cert_chain: []
16
+
17
+ date: 2010-05-10 00:00:00 -04:00
18
+ default_executable:
19
+ dependencies:
20
+ - !ruby/object:Gem::Dependency
21
+ name: rspec
22
+ prerelease: false
23
+ requirement: &id001 !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - ">="
26
+ - !ruby/object:Gem::Version
27
+ segments:
28
+ - 1
29
+ - 2
30
+ - 9
31
+ version: 1.2.9
32
+ type: :development
33
+ version_requirements: *id001
34
+ - !ruby/object:Gem::Dependency
35
+ name: yard
36
+ prerelease: false
37
+ requirement: &id002 !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - ">="
40
+ - !ruby/object:Gem::Version
41
+ segments:
42
+ - 0
43
+ version: "0"
44
+ type: :development
45
+ version_requirements: *id002
46
+ description: String Encryption library
47
+ email: jacaetevha@gmail.com
48
+ executables: []
49
+
50
+ extensions: []
51
+
52
+ extra_rdoc_files:
53
+ - LICENSE
54
+ - README.rdoc
55
+ files:
56
+ - LICENSE
57
+ - README.rdoc
58
+ - Rakefile
59
+ - VERSION
60
+ - lib/lib_string_encryption.rb
61
+ - lib/string_encryption/core_ext.rb
62
+ - lib/string_encryption/encryption.rb
63
+ - lib/string_encryption/secure_random.rb
64
+ - spec/lib_string_encryption_spec.rb
65
+ - spec/spec.opts
66
+ - spec/spec_helper.rb
67
+ has_rdoc: true
68
+ homepage: http://github.com/jacaetevha/lib_string_encryption
69
+ licenses: []
70
+
71
+ post_install_message:
72
+ rdoc_options:
73
+ - --charset=UTF-8
74
+ require_paths:
75
+ - lib
76
+ required_ruby_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ segments:
81
+ - 0
82
+ version: "0"
83
+ required_rubygems_version: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - ">="
86
+ - !ruby/object:Gem::Version
87
+ segments:
88
+ - 0
89
+ version: "0"
90
+ requirements: []
91
+
92
+ rubyforge_project:
93
+ rubygems_version: 1.3.6
94
+ signing_key:
95
+ specification_version: 3
96
+ summary: A library that allows for super simple string encryption
97
+ test_files:
98
+ - spec/lib_string_encryption_spec.rb
99
+ - spec/spec_helper.rb