Module: Rsa::Encrypter
- Defined in:
- lib/rsa-encrypter.rb,
lib/rsa-encrypter/version.rb
Constant Summary collapse
- VERSION =
"0.2.1"
Class Method Summary collapse
- .decrypt(message, d, n) ⇒ Object
- .encrypt(message, e, n) ⇒ Object
- .generate_rsa(a = 5) ⇒ Object
- .ggt(a, b) ⇒ Object
- .prime?(x) ⇒ Boolean
Class Method Details
.decrypt(message, d, n) ⇒ Object
73 74 75 76 77 78 79 |
# File 'lib/rsa-encrypter.rb', line 73 def self.decrypt(, d, n) m = "" .each do |c| m += (c**d % n).to_i.chr end return m end |
.encrypt(message, e, n) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/rsa-encrypter.rb', line 49 def self.encrypt(, e, n) byte = [] ms = [] crypt = [] .each_char do |c| byte << c.ord end byte.each do |b| if b.to_s.length < 3 ms << "0"+b.to_s else ms << b end end ms.each do |b| crypt << c = b.to_i**e % n end return crypt end |
.generate_rsa(a = 5) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/rsa-encrypter.rb', line 34 def self.generate_rsa(a=5) secure = [ [11,13], [61,53], [71,76], [163,181], [443,463], [859,769], [1033,977] ] a-=1 raise "wrong secure level: #{a+1} please use level 1-7" if a > 6 or a < 0 p = prime?(secure[a][0]) q = prime?(secure[a][1]) n = p * q n2 = (p-1)*(q-1) e = (p+q) -1 t = ggt(e, n2) d = t rsa = [n, e, d] return rsa end |
.ggt(a, b) ⇒ Object
5 6 7 8 9 10 11 12 13 14 15 |
# File 'lib/rsa-encrypter.rb', line 5 def self.ggt(a, b) u=t=1 v=s=0 while b > 0 do q=a/b a, b = b, a-q*b u, s = s, u-q*s v, t = t, v-q*t end return u end |
.prime?(x) ⇒ Boolean
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/rsa-encrypter.rb', line 17 def self.prime?(x) if x == 0 or x == 1 return false end i = 2 limit = x / i while i < limit if x % i == 0 raise "#{x} not prime" end i += 1 limit = x / i end return x end |