Golden Ratio Challenge
;;; http://1.61803398874.com/canine | |
;;; Copyright Chris Howey | |
;;; Released under the ISC License | |
;;; | |
;;; To build, use buildapp (http://www.xach.com/lisp/buildapp/): | |
;;; buildapp --output dog --load canine.lisp --entry main | |
;;; | |
(defun list-of-output-streams (list-of-files) | |
(let ((output-streams nil)) | |
(dolist (out-file list-of-files output-streams) | |
(push (open (parse-namestring out-file) :direction :output :element-type '(unsigned-byte 1) :if-exists :supersede) output-streams)))) | |
(defun usage (command) | |
(format *error-output* "Usage: ~%~A FILE... ~%" command)) | |
(defun main (argv) | |
(if (= (length argv) 1) | |
(usage (first argv)) | |
(with-open-stream (out-stream (apply #'make-broadcast-stream (list-of-output-streams (rest argv)))) | |
(loop for val = (read-byte *standard-input* nil) | |
while val | |
do (write-byte val out-stream)) | |
(finish-output out-stream)))) |
;;; Golden Ratio Challenge: http://1.61803398874.com/ | |
;;; https://en.wikipedia.org/wiki/Vigenère_cipher | |
;;; | |
;;; This implements the Vigenere cipher to solve the problem with one addition: | |
;;; Numbers are translated to letters. By glancing over the wikipedia page | |
;;; it seems as though the encryption algorithm is meant only for letters. | |
;;; | |
;;; Copyright Chris Howey | |
;;; Released under the ISC License | |
;;; | |
;;; EXAMPLES: | |
;;; (encrypt-message "attackatdawn" "lemonlemonle") | |
;;; (decrypt-message "xfbhlqtlj" "61803398874") | |
;;; | |
(defun normalized-char-code (letter) | |
(let ((upletter (char-upcase letter))) | |
(if (<= (- (char-code upletter) (char-code #\0)) 9) | |
(- (char-code upletter) (char-code #\0)) | |
(- (char-int upletter) (char-code #\A))))) | |
(defun normalized-code-to-char (code) | |
(code-char (+ (char-code #\A) code))) | |
(defun encrypt-char-to-code (message key) | |
(mod (+ (normalized-char-code message) (normalized-char-code key)) 26)) | |
(defun encrypt-char (message key) | |
(normalized-code-to-char (encrypt-char-to-code message key)) ) | |
(defun encrypt-message (message key) | |
(with-output-to-string (s) | |
(loop for i from 0 to (- (length message) 1) do | |
(princ (encrypt-char (elt message i) (elt key i)) s)))) | |
(defun decrypt-char-to-code (message key) | |
(mod (- (normalized-char-code message) (normalized-char-code key) -26) 26)) | |
(defun decrypt-char (message key) | |
(normalized-code-to-char (decrypt-char-to-code message key)) ) | |
(defun decrypt-message (message key) | |
(with-output-to-string (s) | |
(loop for i from 0 to (- (length message) 1) do | |
(princ (decrypt-char (elt message i) (elt key i)) s)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment