AFIT/Source/builtin/ciphers.ml

105 lines
2.8 KiB
OCaml

(** Ciphers
Built-in integer based ciphers.
*)
open Builtin
open Basic_arithmetics
open Power
(********** Cesar Cipher **********)
(** Cesar's cipher encryption
@param k is an integer corresponding to key
@param m word to cipher.
@param b base ; for ASCII codes should be set to 255.
*)
let encrypt_cesar k m b =
let rec encrypt_cesar_rec l =
match l with
[] -> []
| e::l -> begin
let rot = modulo (e + k) b in
rot::encrypt_cesar_rec l
end
in encrypt_cesar_rec m;;
(** Cesar's cipher decryption
@param k is an integer corresponding to key
@param m encrypted word.
@param b base ; for ASCII code should be set to 255.
*)
let decrypt_cesar k m b =
let rec decrypt_cesar_rec l =
match l with
[] -> []
| e::l -> begin
let rot = modulo (e - k) b in
rot::decrypt_cesar_rec l
end
in decrypt_cesar_rec m;;
(********** RSA Cipher **********)
(** Generate an RSA ciphering keys.
Involved prime numbers need to be distinct. Output is a couple
of public, private keys.
@param p prime number
@param q prime number
*)
let generate_keys_rsa p q =
let n = p * q in
let phi = (p-1) * (q-1) in
let e = phi - 1 in
let (d, _, _) = bezout e phi in
((n, e), (n, d));;
(** Encryption using RSA cryptosystem.
@param m integer hash of message
@param pub_key a tuple (n, e) composing public key of RSA cryptosystem.
*)
let encrypt_rsa m (n, e) = mod_power m e n;;
(** Decryption using RSA cryptosystem.
@param m integer hash of encrypter message.
@param pub_key a tuple (n, d) composing private key of RSA cryptosystem.
*)
let decrypt_rsa m (n , d) = mod_power m d n;;
(********** ElGamal Cipher **********)
(** Generate ElGamal public data. Generates a couple (g, p)
where p is prime and g having high enough order modulo p.
@param p is prime having form 2*q + 1 for prime q.
*)
let rec public_data_g p =
let g = (p - 1)/2 in
(g, p);;
(** Generate ElGamal public data.
@param pub_data a tuple (g, p) of public data for ElGamal cryptosystem.
*)
let generate_keys_g (g, p) =
let r = modulo (787581985456192323) g in
let pub = mod_power g r p in (pub, r);;
(** ElGamal encryption process.
@param msg message to be encrypted.
@param pub_data a tuple (g, p) of ElGamal public data.
@param kA ElGamal public key.
*)
let encrypt_g msg (g, p) kA =
let r = modulo (787581985456192323) g in
let c = mod_power g r p in
let d = msg * mod_power kA r p in
(c, d);;
(** ElGamal decryption process.
@param msg a tuple (msgA, msgB) forming an encrypted ElGamal message.
@param a private key
@param pub_data a tuple (g, p) of public data for ElGamal cryptosystem.
*)
let decrypt_g (msgA, msgB) a (g, p) =
msgB / (mod_power msgA a p);;