-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCiphers.rkt
83 lines (72 loc) · 2.89 KB
/
Ciphers.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#lang racket
; So I can type less
(define (ord char)
(char->integer char))
(define (chr num)
(integer->char num))
; Called by gen-v-key to lengthen or shorten a string to a size 'len',
; cycling back to the start of the string when the end is reached
(define (cycle in len)
(define lst (cond ((list? in) in)
((string? in) (string->list in))
((symbol? in) (string->list (symbol->string in)))))
(define (cyc dst src)
(cond ((= len (length dst)) dst)
((null? src) (cyc dst lst))
(else (cyc (cons (car src) dst) (cdr src)))))
(reverse (cyc null lst)))
; Returns a list of numbers based on the key-word to be used as off-set values in
; the shift function when encrypting a password.
(define (gen-v-key password-len key)
(map (lambda (x) (if (> x 96)
(- x 96)
(- x 64)))
(map ord (cycle key password-len))))
;;; shift
;;; Parameters: Integer num: number to be shifted. should be the ascii value of a letter character.
;;; Integer k: the shift value (Between 0 and 26 inclusive)
;;; Symbol ('encrypt or 'decrypt)
(define (shift num k method)
(if (and (<= k 26) (>= k 0))
(cond ((eq? method 'encrypt)
(cond ((and (>= num 65) (<= num 90))
(if (> (+ num k) 90)
(- (+ num k) 26)
(+ num k)))
((and (>= num 97) (<= num 122))
(if (> (+ num k) 122)
(- (+ num k) 26)
(+ num k)))
(else num)))
((eq? method 'decrypt)
(cond ((and (>= num 65) (<= num 90))
(if (< (- num k) 65)
(+ (- num k) 26)
(- num k)))
((and (>= num 97) (<= num 122))
(if (< (- num k) 97)
(+ (- num k) 26)
(- num k)))
(else num)))
(else (error "Unknown Method: Try 'encrypt or 'decrypt")))
(error "Value of K is not between 0 and 26 (inclusive)")))
;;; Vigenere-Cipher
;;; Parameters: String
;;; String (Characters only)
;;; Symbol ('encrypt or 'decrypt)
(define (vigenere-cipher password keyword method)
(define (folder-proc a b result)
(cons (shift a b method) result))
(define keylist (gen-v-key (string-length password) keyword))
(list->string (map chr (foldr folder-proc '() (map ord (string->list password)) keylist))))
;;; Caesar-Cipher
;;; Parameters: String
;;; Integer (Between 0 and 26 inclusive)
;;; Symbol ('encrypt or 'decrypt)
(define (caesar-cipher password k method)
(list->string
(map chr
(map (lambda(ascii) (shift ascii k method))
(map ord (string->list password))))))
(provide caesar-cipher)
(provide vigenere-cipher)