1
- require " prime"
1
+ require ' prime'
2
2
3
3
def initialize ( keys = { } )
4
4
@e ||= keys [ :e ]
@@ -7,16 +7,16 @@ def initialize(keys = {})
7
7
8
8
def cipher ( message )
9
9
message . bytes . map do |byte |
10
- cbyte = ( ( byte . to_i ** e ) % n ) . to_s
10
+ cbyte = ( ( byte . to_i ** e ) % n ) . to_s
11
11
missing_chars = n . to_s . size - cbyte . size
12
- "0" * missing_chars + cbyte
12
+ '0' * missing_chars + cbyte
13
13
end . join
14
14
end
15
15
16
16
def decipher ( ciphed_message )
17
17
ciphed_message . chars . each_slice ( n . to_s . size ) . map do |arr |
18
- ( arr . join . to_i ** d ) % n
19
- end . pack ( "c*" )
18
+ ( arr . join . to_i ** d ) % n
19
+ end . pack ( 'c*' )
20
20
end
21
21
22
22
def public_keys
@@ -52,43 +52,47 @@ def d
52
52
end
53
53
54
54
def extended_gcd ( a , b )
55
- last_remainder , remainder = a . abs , b . abs
56
- x , last_x , y , last_y = 0 , 1 , 1 , 0
55
+ last_remainder = a . abs
56
+ remainder = b . abs
57
+ x = 0
58
+ last_x = 1
59
+ y = 1
60
+ last_y = 0
57
61
while remainder != 0
58
- last_remainder , ( quotient , remainder ) = remainder , last_remainder . divmod ( remainder )
62
+ ( quotient , remainder ) = last_remainder . divmod ( remainder )
63
+ last_remainder = remainder
59
64
x , last_x = last_x - quotient * x , x
60
65
y , last_y = last_y - quotient * y , y
61
66
end
62
67
63
- return last_remainder , last_x * ( a < 0 ? -1 : 1 )
68
+ [ last_remainder , last_x * ( a < 0 ? -1 : 1 ) ]
64
69
end
65
70
66
71
def invmod ( e , et )
67
72
g , x = extended_gcd ( e , et )
68
- raise "The maths are broken!" if g != 1
73
+ raise 'The maths are broken!' if g != 1
74
+
69
75
x % et
70
76
end
71
77
72
78
def random_prime_number
73
79
number = Random . rand ( 1 ..1000 )
74
- until Prime . prime? ( number ) || number == p || number == q
75
- number = Random . rand ( 1 ..1000 )
76
- end
80
+ number = Random . rand ( 1 ..1000 ) until Prime . prime? ( number ) || number == p || number == q
77
81
number
78
82
end
79
83
80
- def main ( )
81
- puts " Enter the message you want to encrypt and decrypt with RSA algorithm: "
82
- message = gets . chomp ( ) . to_s
83
- puts " Encoded Text:"
84
+ def main
85
+ puts ' Enter the message you want to encrypt and decrypt with RSA algorithm: '
86
+ message = gets . chomp . to_s
87
+ puts ' Encoded Text:'
84
88
puts cipher ( message )
85
- puts " Decoded Text:"
89
+ puts ' Decoded Text:'
86
90
puts decipher ( cipher ( message ) )
87
- puts "p: #{ p ( ) } "
88
- puts "q: #{ q ( ) } "
89
- puts "e: #{ e ( ) } "
90
- puts "d: #{ d ( ) } "
91
- puts "totient: #{ totient ( ) } "
91
+ puts "p: #{ p } "
92
+ puts "q: #{ q } "
93
+ puts "e: #{ e } "
94
+ puts "d: #{ d } "
95
+ puts "totient: #{ totient } "
92
96
end
93
97
94
- main ( )
98
+ main
0 commit comments