Lecture12
Lecture12
Algorithm
Goals:
• To review public-key cryptography
• To demonstrate that confidentiality and sender-authentication can be
achieved simultaneously with public-key cryptography
• To review the RSA algorithm for public-key cryptography
• To present the proof of the RSA algorithm
• To go over the computational issues related to RSA
• To discuss the vulnerabilities of RSA
• Perl and Python implementations for generating primes and for
factorizing medium to large sized numbers
CONTENTS
Section Title Page
12.10.1 The Old RSA Factoring Challenge: Numbers Not Yet Factored 81
Back to TOC
connection with the server. In the context of the security made possible by the SSH
protocol, the public key held by a server is commonly referred to as the server’s host
key. ]
3
Computer and Network Security by Avi Kak Lecture 12
• Every host making its public key available through the kinds
of mechanisms described above solves one of the most vexing
problems associated with symmetric-key cryptography — the
problem of key distribution.
Party A Party B
A’s private key A’s public key B’s public key B’s private key
PRA PUA PUB PRB
Message
Message
Encrypt with PU B Decrypt with PR
B
Party A Party B
A’s private key A’s public key B’s public key B’s private key
PR A PUA PUB PR B
Message
Message
Encrypt with PR A Decrypt with PU
A
Party A Party B
A’s private key A’s public key B’s public key B’s private key
PRA PUA PUB PRB
Message
Message
5
Computer and Network Security by Avi Kak Lecture 12
C = E (P UB , E (P RA, M ))
6
Computer and Network Security by Avi Kak Lecture 12
M = D (P UA, D (P RB , C))
8
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
aφ(n) ≡ 1 (mod n)
9
Computer and Network Security by Avi Kak Lecture 12
10
Computer and Network Security by Avi Kak Lecture 12
11
Computer and Network Security by Avi Kak Lecture 12
C = M e mod n
M = C d mod n
since
12
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
13
Computer and Network Security by Avi Kak Lecture 12
14
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
15
Computer and Network Security by Avi Kak Lecture 12
See Section 11.3 of Lecture 11 for a proof of this. [We will use
this property to go from Equation (5) to Equation (6) in the next subsection.]
16
Computer and Network Security by Avi Kak Lecture 12
17
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
18
Computer and Network Security by Avi Kak Lecture 12
= k × φ(n) (5)
19
Computer and Network Security by Avi Kak Lecture 12
Mp − 1
≡ 1 (mod p)
M k1(p − 1)
≡ 1 (mod p)
20
Computer and Network Security by Avi Kak Lecture 12
21
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
22
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
• You first decide what size (in terms of the number of bits) you
want for the modulus integer n. Let’s say that your
implementation of RSA requires a modulus of size B bits.
– You set the lowest bit of the integer generated by the above
step; this ensures that the number will be odd.
– You also set the two highest bits of the integer; this
ensures that the highest bits of n will be set. (See Section
12.4 for an explanation of why you need to set the first two
bits.)
23
Computer and Network Security by Avi Kak Lecture 12
24
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
25
Computer and Network Security by Avi Kak Lecture 12
to, you may not be able to use a small integer like 3 for e.
p mod e 6 = 1
q mod e 6= 1
27
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
28
Computer and Network Security by Avi Kak Lecture 12
29
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
• Despite the fact that you are not likely to use RSA for content
encryption, it’s nonetheless educational to reflect on how it
could be used for that purpose in the form of a block cipher.
30
Computer and Network Security by Avi Kak Lecture 12
not-so-uncommon usage of the phrase “N-bit block cipher” meaning a cipher that encrypts
• With the modulus size set to 16 bits, we are faced with the
important question of what to use for the size of bit blocks for
conversion into ciphertext as we scan a disk file. Since our
message integer M must be smaller than the modulus n,
obviously our block size cannot equal the modulus size. This
requires that we use a smaller block size, say 8 bits, and, as
mentioned in the next bullet, use padding to fill the rest of the
16 bits. As it turns out, padding is an extremely important part
of RSA ciphers. In addition to the need for padding as
explained here, padding is also needed to make the cipher
resistant to certain vulnerabilities that are described in Section
12.7 of this lecture.
integer M .
• So the issue now is how to find a prime suitable for our 8-bit
representation. Following the prescription given in Section
12.3.1, we could fire up a random number generator, set its first
two bits and the last bit, and then test the resulting number for
its primality with the Miller-Rabin algorithm presented in
Lecture 11. But we don’t need to go to all that trouble for our
toy example. Let’s use the simpler approach described below.
bits of p : 11 − − − − − 1
bits of q : 11 − − − − − 1
where ’−’ denotes the bit that has yet to be determined. As you
can verify quickly from the three bits that are set, such an 8-bit
32
Computer and Network Security by Avi Kak Lecture 12
p = 197
q = 211
which gives us for the modulus n = 197 × 211 = 41567. The bit
pattern for the chosen p, q, and modulus n are:
34
Computer and Network Security by Avi Kak Lecture 12
| = 6 x 41160 + 26633 x 17
where the last equality for the residue 1 uses the fact that the
additive inverse of 14527 modulo 41160 is 26633. [If you don’t like
working out the multiplicative inverse by hand as shown above, you can use the
Python script FindMI.py presented in Section 5.7 of Lecture 5. Another option would
be to use the multiplicative inverse() method of the BitVector class.]
35
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
36
Computer and Network Security by Avi Kak Lecture 12
Vp = C d mod p
Vq = C d mod q
Xp = q × (q −1 mod p)
Xq = p × (p−1 mod q)
+ v
Vp = C d mod p = C u×(p−1) mod p = C v mod p
• When you use FLT in conjunction with CRT, you can calculate
C d (mod n) in roughly quarter of the time it takes
otherwise. [First note, as stated earlier in Section 12.3.1, both p and q are of the order of n/2 where n
is the modulus. Since Vp = C d (mod p) = C d mod(p−1)
(mod p), and since d is of the order of n and
d mod(p − 1) of the order of p (which itself is of the order of n/2), it should take no more than half the
number of multiplications to calculate Vp compared to the number of multiplications needed for calculating
C d (mod n) directly. The same would be true for calculating Vq . As a result, the total number of
multiplications required for both Vp and Vq would be the same as in the direct calculation of C d (mod n).
Note, however, the intermediate results in the modular exponentiation needed for Vp would never exceed p
(and the same would never exceed q for Vq ). Since integer multiplication takes time that is proportional to
the square of the size of the bit fields involved, each multiplication involved in the calculation of Vp and Vq
would take only one-quarter of the time it takes for each multiplication in computing C d (mod n) directly. ]
38
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
AB mod n
B ≡ bk bk−1bk−2 . . . b0 (binary)
B = 2i
X
bi 6=0
i i
bi 6=0 2
P
B
A = A = A2
Y
bi 6=0
40
Computer and Network Security by Avi Kak Lecture 12
Note that as we go from one bit position to the next higher bit
position, we square the previously computed power of A.
i
• The A2 terms in the above product are of the following form
0 1 2 3
A2 , A2 , A2 , A2 , . . .
result = 1
while B > 0:
if B & 1: # check the lowest bit of B
result = ( result * A ) % n
B = B >> 1 # shift B by one bit to right
A = ( A * A ) % n
return result
41
Computer and Network Security by Avi Kak Lecture 12
terminal-interactive Python session with the command script as I did for the session presented
above. First invoke script and then invoke python as shown above. Your interactive work will be
saved in a file called typescript. You can exit the Python session by entering Ctrl-d and then exit
42
Computer and Network Security by Avi Kak Lecture 12
43
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
this session key to the server, the client encrypts it with the server’s public key so that only the server would
be able to decrypt it with its RSA private key. The client sends the encrypted session key to the server and,
44
Computer and Network Security by Avi Kak Lecture 12
45
Computer and Network Security by Avi Kak Lecture 12
46
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
47
Computer and Network Security by Avi Kak Lecture 12
48
Computer and Network Security by Avi Kak Lecture 12
00 || BT || PS || 00 || D
• The fact that RSA could be vulnerable to such attacks was first
discovered by George Davida in 1982.
merely to demonstrate that the attacker can recover the message integer M even with very limited knowledge
that consists of some mechanism informing the attacker whether or not the chosen C ′ violates the structure of
the encryption block that is stipulated for PKCS#1v1.5. Whether or not such a mechanism exists today is
not the point. Such a mechanism could consist of the victim’s RSA engine simply returning an error report
whenever it receives a ciphertext that it believes was produced by a message that did not conform to the
51
Computer and Network Security by Avi Kak Lecture 12
• RSA is made resistant to CCA2 when the padding bytes are set
according to OAEP. OAEP stands for Optimal Asymmetric
Encryption Padding. Unlike what you saw for the
PKCS#1v1.5 format for encryption blocks at the beginning of
this section, there is no structure in the encryption blocks under
PKCS#1v2.x. The padding now involves a mask generation
function that depends on a hash applied to a set of parameters.
For further information, the reader is referred to the RSA Labs
publication “RSAES-OAEP Encryption Scheme” and the
references contained therein. This publication can be download
from the same web site as mentioned at the beginning of this
section.
52
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
be produced within the range of numbers that the output is designed for. For example, if a CSPRNG can
produce 512-bit random numbers with equal probability, its entropy is at its maximum and it equals 512 bits.
However, should the probabilities associated with the output random numbers be nonuniform, the entropy
will be less than 512. The greater the nonuniformity of this probability distribution, the smaller the entropy.
• To see why that is the case, let’s say that p is the common
53
Computer and Network Security by Avi Kak Lecture 12
factor of the two moduli N1 and N2. That makes p the GCD of
N1 and N2. Now let’s denote the other factor in N1 by q1 and
in N2 by q2. You already know from Lecture 5 that Euclid’s
recursion makes the calculation of the GCD of any two numbers
extremely fast. [Using Euclid’s algorithm, the GCD of two 1024-bit integers on a routine
desktop can be computed in just a few microseconds using the Gnu Multiple Precision (GMP) library. More
theoretically speaking, the computational complexity of Euclid’s GCD algorithm is O(n2 ) for n bit
54
Computer and Network Security by Avi Kak Lecture 12
of this earth!
56
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
(282,589,933 – 1)2
This number has over 48 million digits. This is the square of the
largest known prime number, implying that what you see inside
the parentheses is a prime number.
days in RSA cryptography, you have to custom design the algorithms for each attack. Customization
58
Computer and Network Security by Avi Kak Lecture 12
generally consists of making various conjectures about the modulo properties of the factors and using the
]:
conjectures to speed up the search for the factors.
primes, and so on. Modern sieves that are used for fast
factorization are known as quadratic sieve, number
field sieve, etc. The quadratic sieve method is the fastest
for integers under 110 decimal digits and considerably
simpler than the number field sieve. Like the principle
underlying Fermat’s factorization method, the quadratic
sieve method tries to establish congruences modulo n. In
Fermat’s method, we search for a single number x so that
x2 mod n is a square. But such x’s are difficult to find. With
quadratic sieve, we compute x2 mod n for many x’s and
then find a subset of these whose product is a square.
61
Computer and Network Security by Avi Kak Lecture 12
dark when making guesses for a and b, why should we expect a performance any better than
making random guesses for the factors of n up to the square-root of n. That may well be
true in general, but the beauty of searching for the factors via the differences a − b is that it
generalizes to the main feature of the Pollard-ρ algorithm in which the sequence of
integers you choose for b grows twice as fast as the sequence of integers you
choose for a. It is this feature that makes for a much more efficient way to look for the
factors of n. This feature is implemented in lines (E10), (E11), and (E12) of the code shown
at the end of this section. As was demonstrated by Pollard, letting b grow twice as fast as a
in gcd(a − b, n) makes for fast detection of cycles, these being two different numbers a and b
#!/usr/bin/env python
## Factorize.py
## Author: Avi Kak
## Date: February 26, 2011
## Modified: Febrary 25, 2012
## Uncomment line (F9) and comment out line (F10) if you want to see the results
## with the simpler form of the Pollard-Rho algorithm.
import random
import sys
64
Computer and Network Security by Avi Kak Lecture 12
65
Computer and Network Security by Avi Kak Lecture 12
Factorize.py 18446744073709551617
274177 ^ 1
67280421310721 ^ 1
66
Computer and Network Security by Avi Kak Lecture 12
notice that you will get the same in only another blink of the
eye if you comment out line (F10) and uncomment line (F9),
which basically amounts to making a random guess for the
factors.
1308520867 ^ 1
7660450463 ^ 1
11579208923731619542357098500868790785326998466564056403
67
Computer and Network Security by Avi Kak Lecture 12
23 ^ 1
41 ^ 1
149 ^ 1
40076041 ^ 1
713526132967 ^ 1
9962712838657 ^ 1
289273479972424951 ^ 1
#!/usr/bin/env perl
## Factorize.pl
## Author: Avi Kak
## Date: February 19, 2016
## Uncomment line (F12) and comment out line (F13) if you want to see the results
## with the simpler form of the Pollard-Rho algorithm.
use strict;
use warnings;
die "Your number is too large for factorization by this script. " .
"Instead, try the script ’FactorizeWithBigInt.pl’\n"
if $p > 0x7f_ff_ff_ff; #(A3)
68
Computer and Network Security by Avi Kak Lecture 12
69
Computer and Network Security by Avi Kak Lecture 12
$primeflag = 1; #(P25)
last; #(P26)
}
}
return 0 if ! $primeflag; #(P27)
}
my $probability_of_prime = 1 - 1.0/(4 ** scalar(@probes)); #(P28)
return $probability_of_prime; #(P29)
}
70
Computer and Network Security by Avi Kak Lecture 12
– If you call the above script with the argument shown below
Factorize.pl 1844674407
the script will return the answer shown below:
Factors of 1844674407:
3 ^ 2
204963823 ^ 1
– On the other hand, if you call this script for a large integer,
as in
Factorize.pl 18446744073709551617
#!/usr/bin/env perl
## FactorizeWithBigInt.pl
## Author: Avi Kak
## Date: February 21, 2016
## Uncomment line (F13) and comment out line (F14) if you want to see the results
## with the simpler form of the Pollard-Rho algorithm.
72
Computer and Network Security by Avi Kak Lecture 12
use strict;
use warnings;
use Math::BigInt;
use Math::BigInt::Random::OO;
73
Computer and Network Security by Avi Kak Lecture 12
}
my ($a_raised_to_q, $a_raised_to_jq, $primeflag); #(P14)
foreach my $a (@probes) { #(P15)
my $abig = Math::BigInt->new("$a"); #(P16)
my $a_raised_to_q = $abig->bmodpow($q, $p); #(P17)
next if $a_raised_to_q->is_one(); #(P18)
my $pdec = $p->copy()->bdec(); #(P19)
next if ($a_raised_to_q->bcmp($pdec) == 0) && ($k > 0); #(P20)
$a_raised_to_jq = $a_raised_to_q; #(P21)
$primeflag = 0; #(P22)
foreach my $j (0 .. $k - 2) { #(P23)
my $two = Math::BigInt->new("2"); #(P24)
$a_raised_to_jq = $a_raised_to_jq->copy()->bmodpow($two, $p); #(P25)
if ($a_raised_to_jq->bcmp( $p->copy()->bdec() ) == 0 ) { #(P26)
$primeflag = 1; #(P27)
last; #(P28)
}
}
return 0 if ! $primeflag; #(P29)
}
my $probability_of_prime = 1 - 1.0/(4 ** scalar(@probes)); #(P30)
return $probability_of_prime; #(P31)
}
74
Computer and Network Security by Avi Kak Lecture 12
my $p = shift; #(R3)
my @probes = qw[ 2 3 5 7 11 13 17 ]; #(R4)
foreach my $a (@probes) { #(R5)
my $abig = Math::BigInt->new("$a"); #(R6)
return $abig if $p->copy()->bmod($abig)->is_zero(); #(R7)
}
my $d = Math::BigInt->bone(); #(R8)
my $randgen = Math::BigInt::Random::OO->new( max => $p ); #(R9)
my $a = Math::BigInt->new(); #(R10)
unless ($a->numify() >= 2) { #(R11)
$a = $randgen->generate(1); #(R12)
}
$randgen = Math::BigInt::Random::OO->new( max => $p ); #(R13)
my $c = Math::BigInt->new(); #(R14)
unless ($c->numify() >= 2) { #(R15)
$c = $randgen->generate(1); #(R16)
}
my $b = $a->copy(); #(R17)
while ($d->is_one()) { #(R18)
$a->bmuladd($a->copy(), $c->copy())->bmod($p); #(R19)
$b->bmuladd($b->copy(), $c->copy())->bmod($p); #(R20)
$b->bmuladd($b->copy(), $c->copy())->bmod($p); #(R21)
$d = Math::BigInt::bgcd( $a->copy()->bsub($b), $p ); #(R22)
last if $d->bacmp(Math::BigInt->bone()) > 0; #(R23)
}
return $d; #(R24)
}
75
Computer and Network Security by Avi Kak Lecture 12
3 ^ 3
7 ^ 1
11 ^ 1
13 ^ 1
19 ^ 1
757 ^ 1
3607 ^ 1
3803 ^ 1
52579 ^ 1
70541929 ^ 1
14175966169 ^ 1
440334654777631 ^ 1
76
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
RSA-XXX
79258699544783330333470858414800596877379758573642
19960734330341455767872818152135381409304740185467
78
Computer and Network Security by Avi Kak Lecture 12
Name: RSA-768
79
Computer and Network Security by Avi Kak Lecture 12
80
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
Name: RSA-896
Prize: $75000 (retracted)
Digits: 270
Digit Sum: 1222
41202343698665954385553136533257594817981169984
43279828454556264338764455652484261980988704231
61841879261420247188869492560931776375033421130
98239748515094490910691026986103186270411488086
69705649029036536588674337317208131041051908642
54793282601391257624033946373269391
Name: RSA-1024
Prize: $100000 (retracted)
Digits: 309
Digit Sum: 1369
135066410865995223349603216278805969938881475605
667027524485143851526510604859533833940287150571
909441798207282164471551373680419703964191743046
496589274256239341020864383202110372958725762358
509643110564073501508187510676594629205563685529
475213500852879416377328533906109750544334999811
150056977236890927563
81
Computer and Network Security by Avi Kak Lecture 12
Name: RSA-1536
Prize: $150000 (retracted)
Digits: 463
Digit Sum: 2153
184769970321174147430683562020016440301854933866
341017147178577491065169671116124985933768430543
574458561606154457179405222971773252466096064694
607124962372044202226975675668737842756238950876
467844093328515749657884341508847552829818672645
133986336493190808467199043187438128336350279547
028265329780293491615581188104984490831954500984
839377522725705257859194499387007369575568843693
381277961308923039256969525326162082367649031603
6551371447913932347169566988069
Name: RSA-2048
Prize: $200000 (retracted)
Digits: 617
Digit Sum: 2738
2519590847565789349402718324004839857142928212620
4032027777137836043662020707595556264018525880784
4069182906412495150821892985591491761845028084891
2007284499268739280728777673597141834727026189637
5014971824691165077613379859095700097330459748808
4284017974291006424586918171951187461215151726546
3228221686998754918242243363725908514186546204357
6798423387184774447920739934236584823824281198163
8150106748104516603773060562016196762561338441436
0383390441495263443219011465754445417842402092461
6515723350778707749817125772467962926386356373289
9121548314381678998850404453640235273819513786365
64391212010397122822120720357
82
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
• The main goal of this section is to explain how the public and
the private keys — which theoretically speaking are merely
pairs of integers [n, e] and [n, d], respectively, — are actually
represented in the memory of a computer. As you will see, the
representation used depends on the protocol. The key
representation in the SSH protocol is, for example, very different
from the key representation in the TLS/SSL protocol. However,
before getting to the key representation issues, what follows are
some very important general comments about the RSA
algorithm.
• The size of the key in the RSA algorithm typically refers to the
size of the modulus integer in bits. In that sense, the phrase
“key size” in the context of RSA is a bit of a misnomer. As
you now know, the actual keys in RSA are the public key [n, e]
and the private key [n, d]. In addition to depending on the size
of the modulus, the key sizes obviously depend on the values
chosen for e and d.
the RSA algorithm that uses a 1024 bit modulus. [It is interesting to
reflect on the fact that 1024 bits can be stored in only 128 bytes in the memory of a computer (and
that translates into a 256-character hex string if we had to print out the 128 bytes for visual display),
yet the decimal value of the integer represented by these 128 bytes can be monstrously
There are 359 decimal digits in this very large integer. [It is
trivial to generate arbitrarily large integers in Python since the language places no
limits on the size of the integer. I generated the above number by simply setting a
variable to a random 256 character hex string by a statement like
num = 0x7fafdbff7fe0f9ff7.... 256 hex characters ...... ff7fffda5f
and then just calling ’print num’.]
84
Computer and Network Security by Avi Kak Lecture 12
• Doubling the size of the key (meaning the size of the modulus)
will, in general, increase the time required for public key
operations (as needed for encryption or signature verification)
by a factor of four and increase the time taken by private key
operations (decryption and signing) by a factor of eight. Public
key operations are not as affected as the private key operations
when you double the size of the key is because the public key
exponent e does not have to change as the key size increases.
On the other hand, the private key exponent d changes in direct
proportion to the size of the modulus. The key generation time
goes up by a factor of 16 as the size of the key (meaning the size
of the modulus) is doubled. But key generation is a relatively
infrequent operation. (Ref.: http://www.rsa.com/rsalabs)
• The public and the private keys are stored in particular formats
specified by various protocols. For the public key, in addition to
storing the encryption exponent and the modulus, the key may
also include information such as the time period of validity,
the name of the algorithm used for key generation, etc. For
the private key, in addition to storing the decryption exponent
and the modulus, the key may include additional information
along the same lines as for the public key, and, additionally, the
corresponding public key also. Typically, the formats call for
the keys to be stored using Base64 encoding so that they can be
displayed using printable characters. (See Lecture 2 on Base64
encoding.) To see such keys, you could, for example, experiment
with the following function:
85
Computer and Network Security by Avi Kak Lecture 12
ssh-keygen -t rsa
The public and the private keys returned by this call, when
stored appropriately, will allow your laptop to establish SSH
connections with machines elsewhere from virtually anywhere in
the world (unless a local firewall blocks SSH traffic) without
you having to log in explicitly with a password. [You
can also replace ‘rsa’ with ‘dsa’ in the above call. The flag ‘dsa’ refers to the Digital
Signature Algorithm that typically uses the ElGamal protocol (see Section 13.6 of
Lecture 13 for ElGamal) for generating the key pairs. A call such as above will ask
you for a passphrase, but you can ignore it if you wish. The above call will store the
private key in the file .ssh/id rsa of the home account in your laptop. The public
key will be deposited in a file that will be named .ssh/id rsa.pub. Execute the
above command on your laptop and then copy the public key that is
generated into the file .ssh/authorized keys in your own account of the
remote machine to which you want SSH access without the bother of
having to log in with a password.]
86
Computer and Network Security by Avi Kak Lecture 12
MIIEpAIBAAKCAQEAt/lgFURxL351WHaOhLzRHeWBfgt2vomE4nEl08CDtscn0yl7
UMj08B0T896QGuSPvMhFu/I5aGCM4SS7W4wPMxYlnpohKQNCOFFClLxh8AusF5NC
sZSDoRpsG02EBFtUVvzRoQcBpDQoEbbrZ60/cZEve/59z6tIexBbw19LlWAnWqO2
Q33p12mOmuNlcP+StE55Dlz828cCSStyiOtru+Z3DyMhc8D7uBDbrsXchV2dE8tf
6zpIorheFwO4iJ+0YQSaKNc7GpPJEXayBslpVeb5Dp1uZcSDWhJD5dkvpgngmGfJ
FjMuz2FhpCG7msojn1OMOG0JkrpMjMjDnRs7KwIDAQABAoIBAQCfywcskbzprqIH
yznwivvrRruZmiVyS4nTEMn1SUJeEE9D9sS4H0O4BtmcuRRbd2htZVpEa5h3U10p
9LiTRGyzR6o3PtJMiBsNRW9aNuGuGMVJ2MtV6JQH6yY49LQVAKqZv4/omGhRkke3
UzTWYUE4yA0BWsM2DCSxVz0MzgmdXGJ/s3ARcj2hetfN4FUjBg7TenSoIcb+2XA+
0B6l0sr5R3DvStl/erqwlywkA+IeX2Bvqn31yHwoSYqcxZ/eKYxn5BnRTjtXrnNE
W9LBb6Au4Ch1yzkpgCos/kGVb2nzQIKvlFbISD3FhL9hNrL9u2Wnlm9ee9umgLC8
qTiK6QFBAoGBAPM4q700n7nOFtB/zoZn9bO63dfKdZ/QuOudrgJjhygRVXIQlPyi
ZzRjdTDtfTY9DlMk6GqTpeTgVjKARE2C72Uip0Ba5s4/8lhdlvlgJjJ9w1S8LcXm
fySVHEd6vJSZ9CiaA75jybwYIlETitP3d92/nPWY7iOi67ctXaREPkphAoGBAMGj
1BzH2qcEsX/flOMMv3ou0lnq2cfw9tdw8B4DFrfeBdO2z4yOO18hi9sPSO/P7Zzb
1hfgK3RRxJJcHYVwuibObvj4n3LHAV0LuCYlRoEIt7IzbuTTQbOsWqxtHz5sGH+T
G4Vpe8iLHdEMsA2Gm911xjwURYshTFqfdKtX1KkLAoGBANaPScGRqM4qpimsda5Q
C4pP8OAqdHVVlawU36qvzk1kbTJAuo3bXpvymTFecDTmy7pBNt69/XzZAnFugdK3
DST02wKErlOISev2M/cuAMRN+YDIuMB6Q/Mrr1THS5Dz91XR+Dd+pDpQOAW57aBs
EMwH+xkVng7F7JcdaBw/L4xBAoGAM4wPHRI+rJNdRPMZyU9NcZMhP/p6uvT0YOmZ
ogOkepHJ71AM9BewymQ9vLTW76/kSwtidLyiFLbnoyaOXUVi6I2vkOtuVrmPLVu/
S7hEinjtnax/ar6qENBi2t+5n35bDyrz+pHX98zAxTOhchhRSaTefoPO93iHwOAN
yMb6v30CgYALPSHHlRCgWSd/0rqykPwzGACobm9a4Pth8YtuOSdHHfnkf2CoU3Go
y6gDXV/0k0NL9HF33A9mgXa3H0uj5hYLswRcWwmlWex6ytavFbsRwykKHRHMp9w5
iLz2nnDdZ9DwhBtsSjq948TZYoD9mGg/PZabLjBsicTtjSvCIrP1FQ==
-----END RSA PRIVATE KEY-----
• And here is an example of the public key that goes with the
private key shown above:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC3+WAVRHEvfnVYdo6EvNEd5YF+C3
a+iYTicSXTwIO2xyfTKXtQyPTwHRPz3pAa5I+8yEW78jloYIzhJLtbjA8zFiWemiEp
A0I4UUKUvGHwC6wXk0KxlIOhGmwbTYQEW1RW/NGhBwGkNCgRtutnrT9xkS97/n3Pq0
h7EFvDX0uVYCdao7ZDfenXaY6a42Vw/5K0TnkOXPzbxwJJK3KI62u75ncPIyFzwPu4
ENuuxdyFXZ0Ty1/rOkiiuF4XA7iIn7RhBJoo1zsak8kRdrIGyWlV5vkOnW5lxINaEk
Pl2S+mCeCYZ8kWMy7PYWGkIbuayiOfU4w4bQmSukyMyMOdGzsr kak@pixie
three fields separated by white space: (1) the key type; (2) a
chunk of Base64 encoded data; and (3) A comment. In the
public key that I showed above, the first and the third fields are,
respectively, the strings ‘ssh-rsa’ and ‘kak@pixie’. What is
in-between the two is the Base64 encoded data that holds the
public exponent and the modulus integers. After you
Base64-decode this string, you end up with a stream of bytes for
three <length data> records. These three records hold the
following three pieces of information: (1) Algorithm name
(which would be the same as the key-type you would have seen
in the first field of the public key; (2) the RSA public exponent;
and (3) the RSA modulus. In each record, the length value is
stored in the first four bytes in the Big-endian form. [Therefore,
in order to extract the (e, n) integers from the key shown above, we must scan the byte stream that we get
after Base64 decoding of the middle field shown above. We look at the first four bytes to see how many
subsequent bytes hold the name of the algorithm. After we have read off those bytes, we again look at the
next four bytes to find out how many subsequent bytes hold the public exponent; and so on for extracting the
88
Computer and Network Security by Avi Kak Lecture 12
#!/usr/bin/env python
## extract_sshpubkey_params.py
## Author: Avi Kak
## Date: February 11, 2013
import sys
import base64
import BitVector
if len(sys.argv) != 2:
sys.stderr.write("Usage: %s <public key file>\n" % sys.argv[0])
sys.exit(1)
keydata = base64.b64decode(open(sys.argv[1]).read().split(None)[1])
bv = BitVector.BitVector( rawbytes = keydata )
parts = []
while bv.length() > 0:
bv_length = int(bv[:32]) # read 4 bytes for length of data
data_bv = bv[32:32+bv_length*8] # read the data
parts.append(data_bv)
bv.shift_left(32+bv_length*8) # shift the starting BV and
bv = bv[0:-32-bv_length*8] # and truncate its length
public_exponent = int(parts[1])
modulus = int(parts[2])
print "public exponent: ", public_exponent
print "modulus: ", modulus
extract_sshpubkey_params.py ~/.ssh/id_rsa.pub
public exponent: 35
modulus: 28992239265965680130833686108835390387986295644147105350109222053494471862488069515097328563379
83891022841669525585184878497657164390613162380624769814604174911672498450880421371197440983388
47257142771415372626026723527808024668042801683207069068148652181723508612356368518824921733281
43920627731421841448660007107587358412377023141585968920645470981284870961025863780564707807073
26000355974893593324676938927020360090167303189496460600023756410428250646775191158351910891625
48335568714591065003819759709855208965198762621002125196213207135126179267804883812905682728422
31250173298006999624238138047631459357691872217
89
Computer and Network Security by Avi Kak Lecture 12
• The SSL/TLS public and private keys, as also the SSH RSA
private keys, are, on the other hand, stored using a more
elaborate procedure: The key information is first encoded using
Abstract Syntax Notation (ASN) according to the ASN.1
standard and the resulting data structure DER-encoded into a
byte stream. (DER standards for ‘Distinguished Encoding
Rules’ — it’s a part of the ASN.1 standard.) Finally, the byte
stream thus generated is turned into a printable representation
by Base64 encoding. [The ASN.1 standard, along with one of its transfer encodings such as
DER, accomplishes the same thing for complex data structures in a binary format that the XML standard
does in a textual format. You can certainly convert XML representations into binary formats, but the
resulting encoding will, in general, be much longer than those produced by ASN.1. Let’s say you wish to
represent all of your assets in a manner that would be directly readable by different computing platforms and
different programming languages. A record of your assets is likely to consist of the names of the financial
institutions and the value of the assets held by them, a listing of your fixed assets, such as real estate
properties and their worth, etc. In general, such data will require a tree representation in which the various
nodes may stand for the names of the financial institutions or the names of the assets and the children of the
leaf nodes would consist of asset values. The values for some of the nodes may be in the form of ordered lists,
unordered lists (sets), key-value pairs, etc. ASN.1 creates compact byte level representations for such
structures that is portable across platforms and languages. Just to give you a small taste of the flexibility of
ASN.1 representation, it places no constraints on the size of any of the symbolic entities or any of the
numerical values. And to also give you a taste of the secret to the sauce, when ASN.1 is used with BER
(Basic Encoding Rules) encoding, each node of the tree is represented by three blocks of bytes: (1)
Identification block of an unlimited number of bytes; (2) Length block of an unlimited number of bytes; and
(3) Value block of an unlimited number of bytes.The important thing to note here is there are no constraints
on how many bytes are taken up by each of the thee blocks. How does ASN.1 accomplish that? It’s all done
by using high-end bytes to carry information about bytes further downstream. For example, if the length is to
be represented by a single byte, then the value of length must not exceed 128. However, if the value of length
90
Computer and Network Security by Avi Kak Lecture 12
is 128 or greater, then the most significant bit of the first byte must be set to 1 and the trailing bits must tell
us how many of the following bytes are being used for storing the length information. Similar rules are used
where the first command creates a private key for a 1024 bit
modulus and the second then gives you the corresponding
public key. The private key will be deposited in the file
myprivate.pem and the public key in the file mypublic.pem.
• If you want to see the modulus and the public exponent used in
the public key, you can execute
openssl rsa -pubin -inform PEM -text -noout < mypublic.pem
91
Computer and Network Security by Avi Kak Lecture 12
formatting of such keys are RFC 3447 and 4716. ] The ASN.1 representation of a
public RSA key is given by:
SEQUENCE {
SEQUENCE {
OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1),
NULL
}
BIT STRING {
RSAPublicKey ::= SEQUENCE {
modulus INTEGER, -- n
publicExponent INTEGER -- e
}
}
}
the byte-stream representation of the object. These keywords themselves do not appear directly in their
symbolic forms in the byte level representation of a key. An agent receiving such a key would know its
”schema” from the object identifier and would thus be able to decode the bytes.]
92
Computer and Network Security by Avi Kak Lecture 12
93
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
12.12 IN SUMMARY . . .
• Assuming that you are using the best possible random number
generators to create candidates for the primes that are needed
and that you also use a recent version of the RSA scheme that
is resistant to the chosen ciphertext attacks, the security of RSA
encryption depends critically on the difficulty of factoring large
integers.
• These days you are unlikely to use a key whose length is — or, to
Barker et al. ]
94
Computer and Network Security by Avi Kak Lecture 12
Symmetric Key Algorithm Key Size for the Comparable RSA Key Length
Symmetric Key Algorithm for the Same Level of Security
• However, RSA is ideal for the exchange of secret keys that can
subsequently be used for the more traditional (and much faster)
symmetric-key encryption and decryption of the message
content.
95
Computer and Network Security by Avi Kak Lecture 12
Back to TOC
96
Computer and Network Security by Avi Kak Lecture 12
C = M e (mod n)
Since the enemy will know your public key, he will know that
what your business partner has sent you is C = M e where e is
the public exponent that the enemy would know about.
Assuming for the sake of convenience that e = 3, why can’t the
97
Computer and Network Security by Avi Kak Lecture 12
7. Programming Assignment:
In each public key, the first integer is the modulus n and the
second the encryption integer e. Now use the Chinese
Remainder Theorem of Section 11.7 in Lecture 11 to show how
you can reconstruct M 3, which in this case would be 1000, from
the three ciphertext values corresponding to the three public
keys. [HINT: If you are using Python, the ciphertext value in each case is returned by the built-in
3-argument function pow(). For example, pow(M, 3, 29) will return the ciphertext integer C1 for the first
public key shown above. For each public key, we have Ci = M 3 mod ni where the three moduli are denoted
n1 = 29, n2 = 37, and n3 = 41. Now to solve the problem, you can reason as follows: Since n1 , n2 , and n3
are pairwise co-prime, CRT allows us to reconstruct M 3 modulo N = n1 × n2 × n3 . This will require that you
find Ni = N/ni for i = 1, 2, 3. And then you would need to find the multiplicative inverse of each Ni modulo
its corresponding ni . Let Niinv denote this multiplicative inverse. You can use the Python
multiplicative-inverse calculator shown in Section 5.7 of Lecture 5 to calculate the Niinv values. Then, by
CRT, you should be able to recover M 3 by (C1 × N1 × N1inv + C2 × N2 × N2inv + C3 × N3 × N3inv ) mod N . ]
98
Computer and Network Security by Avi Kak Lecture 12
8. Programming Assignment:
#!/usr/bin/env python
## PrimeGenerator.py
## Author: Avi Kak
## Date: February 18, 2011
## Modified Date: February 28, 2016
## Call syntax:
##
## PrimeGenerator.py width_desired_for_bit_field_for_prime
##
## For example, if you call
##
## PrimeGenerator.py 32
##
## you may get a prime that looks like 3262037833. On the other hand, if you
## call
##
## PrimeGenerator.py 128
##
## you may get a prime that looks like 338816507393364952656338247029475569761
##
## IMPORTANT: The two most significant are explicitly set for the prime that is
## returned.
import sys
import random
99
Computer and Network Security by Avi Kak Lecture 12
100
Computer and Network Security by Avi Kak Lecture 12
if self.test_candidate_for_prime(): #(E8)
if self.debug: #(E9)
print("Prime number: %d with probability %f\n" %
(self.candidate, self.probability_of_prime) ) #(E10)
break #(E11)
else: #(E12)
if max_reached: #(E13)
self.candidate -= 2 #(E14)
elif self.candidate >= self._largest - 2: #(E15)
max_reached = 1 #(E16)
self.candidate -= 2 #(E17)
else: #(E18)
self.candidate += 2 #(E19)
if self.debug: #(E20)
print(" candidate is: %d" % self.candidate) #(E21)
return self.candidate #(E22)
the script will return a full-width 64-bit prime that will look like:
Prime returned: 17828589080991197309
#!/usr/bin/env perl
## PrimeGenerator.pl
## Author: Avi Kak
## Date: February 26, 2016
## Call syntax:
##
## PrimeGenerator.pl width_desired_for_bit_field_for_prime
##
## For example, if you call
##
## PrimeGenerator.pl 32
##
## you may get a prime that looks like 3340094299. On the other hand, if you
## call
##
## PrimeGenerator.pl 128
##
## you may get a prime that looks like 333618953930748159614512936853740718827
##
## IMPORTANT: The two most significant are explicitly set for the prime that is
## returned.
use strict;
use warnings;
use Math::BigInt;
102
Computer and Network Security by Avi Kak Lecture 12
103
Computer and Network Security by Avi Kak Lecture 12
} else { #(E12)
if ($max_reached ) { #(E13)
$self->{candidate} -= 2; #(E14)
} elsif ($self->{candidate} >= $self->{_largest} - 2) { #(E15)
$max_reached = 1; #(E16)
$self->{candidate} -= 2; #(E17)
} else { #(E18)
$self->{candidate} += 2; #(E19)
}
}
}
return $self->{candidate}; #(E20)
}
1;
################################ main ########################################
package main;
A call such as the one shown below for generating a 256 bit
prime
PrimeGenerator.pl 256
9. Programming Assignment:
105