Module: LazyRsa

Defined in:
lib/lazy_rsa.rb

Defined Under Namespace

Classes: KeyParams

Constant Summary collapse

SECURE_EXPONENT =
0xECE669597141FAC8A699C75294E7E087698EAD0B32D58F4A17DC016B0483E3B9163B666AFC8D251B69F180B3902BB6238D7BAE57AF938DD8484F98B5790E8D96FBB5F2A0207497F9AEEEBECED882F0F55540443B5FA1221DF5688DE1F89E9A5801AFFAA82A5A4D213938CD08479DEE3A13974144C9F624CEA7E0DE246F00635D
SECURE_MODULUS =
0x48D4498B62509947218CD104794AF6DBB6498F5CCCFCCACA57BF4E6FC9BDAAFAE06341F118430BCE33B5304AB8EEF60A7E53466E92965EB716C6673F5D3B726923FF699F1B197E941870D8DFC9C740A7DE9C92F10C151CCB0405E1960CB62A5547037FD3CD1FC2C1F7BF4899A971D0D1E4D5E6C1676F03645658CB66744D3BDD84E5C316163CE4AA7B8205F784CC0012B19951DDF90920858C4DA9A4BCC6D21C55BB164C74EAB2817556598AF9D7AFF2F703E46AC7D5E9250C7C04B0B1603EABA11A31EF0B99D7F75277EF624E436C9ADD8D3DC614BC325C36A0025DF3E0C2259C89D2AC482D8DF9AC6670F6A45C4D42D310948D5298634868981F121F185C5B

Class Method Summary collapse

Class Method Details

.build_key(e: nil, d: nil, n:) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/lazy_rsa.rb', line 32

def build_key(e: nil, d: nil, n:)
  data_sequence = OpenSSL::ASN1::Sequence([
    OpenSSL::ASN1::Integer(n),
    OpenSSL::ASN1::Integer(e),
    OpenSSL::ASN1::Integer(d),
  ])
  asn1 = OpenSSL::ASN1::Sequence(data_sequence)
  OpenSSL::PKey::RSA.new(asn1.to_der)
end

.decrypt(key, ciphertext) ⇒ Object



12
13
14
15
16
# File 'lib/lazy_rsa.rb', line 12

def decrypt(key, ciphertext)
  key = read_key(key)
  integer = OpenSSL::BN.new(ciphertext).mod_exp(key.d, key.n)
  integer_to_text(integer)
end

.encrypt(key, plaintext) ⇒ Object



7
8
9
10
# File 'lib/lazy_rsa.rb', line 7

def encrypt(key, plaintext)
  key = read_key(key)
  text_to_integer(plaintext).mod_exp(key.e, key.n).to_i
end

.generate_keyObject



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/lazy_rsa.rb', line 18

def generate_key
  q = OpenSSL::BN.generate_prime(512)
  phi = OpenSSL::BN.new(0)
  while q.gcd(phi) != 1
    p = OpenSSL::BN.generate_prime(512)
    phi = (p - 1) * (q - 1)
  end
  n = p * q
  e = p.mod_exp(SECURE_EXPONENT, SECURE_MODULUS)
  d = e.mod_inverse(phi)

  build_key(e:, d:, n:)
end