Skip to content

Instantly share code, notes, and snippets.

@k4rtik
Created December 9, 2011 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k4rtik/1453425 to your computer and use it in GitHub Desktop.
Save k4rtik/1453425 to your computer and use it in GitHub Desktop.
Number Theory & Cryptography - Assignement 2 - Question 3: Implement RSA Cryptosystem. - Done with Aviral - November 10, 2011
/* Question 3: Implement RSA Cryptosystem. */
/*
Call keygen function first.
Use the key generated to encrypt and decrypt message using
corresponding functions.
*/
fastexp(a, x, n) = {
c = 0;
d = 1;
m = binary(x);
i = length(m);
while( (i>0),
c = 2 * c;
d = (d*d) % n;
if( ( m[i]==1 ),
c = c + 1;
d = (a*d) % n;
);
i = i - 1;
);
return(d);
}
rsaen(p, e, n) = {
C = fastexp(p, e, n);
print("Encrypted value is ", C);
}
rsadec(c, d, n) = {
p = fastexp(c, d, n);
print("Decrypted value is ", p);
}
/* p, q are large distinct prime numbers */
rsakeygen(p, q) = {
n = p * q;
phi = (p-1) * (q-1);
e = random(phi);
while( gcd(e,phi) != 1,
e = random(phi)
);
d = 1;
while( ( ((e*d) % phi) != 1 ),
d++;
);
print("Public key is n = "n", e = " e);
print("Private key is d = " d);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment