September Morn Update

This commit is contained in:
Ingy döt Net 2019-09-12 10:33:56 -07:00
parent 4e2d22a71d
commit aac6731f2c
6856 changed files with 141342 additions and 21127 deletions

View file

@ -0,0 +1,30 @@
* Caesar cypher 04/01/2019
CAESARO PROLOG
XPRNT PHRASE,L'PHRASE print phrase
LH R3,OFFSET offset
BAL R14,CYPHER call cypher
LNR R3,R3 -offset
BAL R14,CYPHER call cypher
EPILOG
CYPHER LA R4,REF(R3) @ref+offset
MVC A,0(R4) for A to I
MVC J,9(R4) for J to R
MVC S,18(R4) for S to Z
TR PHRASE,TABLE translate
XPRNT PHRASE,L'PHRASE print phrase
BR R14 return
OFFSET DC H'22' between -25 and +25
PHRASE DC CL37'THE FIVE BOXING WIZARDS JUMP QUICKLY'
DC CL26'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
REF DC CL26'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
DC CL26'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
TABLE DC CL256' ' translate table for TR
ORG TABLE+C'A'
A DS CL9
ORG TABLE+C'J'
J DS CL9
ORG TABLE+C'S'
S DS CL8
ORG
YREGS
END CAESARO

View file

@ -0,0 +1,172 @@
/* ARM assembly Raspberry PI */
/* program caresarcode.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ STRINGSIZE, 500
/* Initialized data */
.data
szMessString: .asciz "String :\n"
szMessEncrip: .asciz "\nEncrypted :\n"
szMessDecrip: .asciz "\nDecrypted :\n"
szString1: .asciz "Why study medicine because there is internet ?"
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
szString2: .skip STRINGSIZE
szString3: .skip STRINGSIZE
/* code section */
.text
.global main
main:
ldr r0,iAdrszMessString @ display message
bl affichageMess
ldr r0,iAdrszString1 @ display string
bl affichageMess
ldr r0,iAdrszString1
ldr r1,iAdrszString2
mov r2,#20 @ key
bl encrypt
ldr r0,iAdrszMessEncrip
bl affichageMess
ldr r0,iAdrszString2 @ display string
bl affichageMess
ldr r0,iAdrszString2
ldr r1,iAdrszString3
mov r2,#20 @ key
bl decrypt
ldr r0,iAdrszMessDecrip
bl affichageMess
ldr r0,iAdrszString3 @ display string
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessString: .int szMessString
iAdrszMessDecrip: .int szMessDecrip
iAdrszMessEncrip: .int szMessEncrip
iAdrszString1: .int szString1
iAdrszString2: .int szString2
iAdrszString3: .int szString2
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* encrypt strings */
/******************************************************************/
/* r0 contains the address of the string1 */
/* r1 contains the address of the encrypted string */
/* r2 contains the key (1-25) */
encrypt:
push {r3,r4,lr} @ save registers
mov r3,#0 @ counter byte string 1
1:
ldrb r4,[r0,r3] @ load byte string 1
cmp r4,#0 @ zero final ?
streqb r4,[r1,r3]
moveq r0,r3
beq 100f
cmp r4,#65 @ < A ?
strltb r4,[r1,r3]
addlt r3,#1
blt 1b
cmp r4,#90 @ > Z
bgt 2f
add r4,r2 @ add key
cmp r4,#90 @ > Z
subgt r4,#26
strb r4,[r1,r3]
add r3,#1
b 1b
2:
cmp r4,#97 @ < a ?
strltb r4,[r1,r3]
addlt r3,#1
blt 1b
cmp r4,#122 @> z
strgtb r4,[r1,r3]
addgt r3,#1
bgt 1b
add r4,r2
cmp r4,#122
subgt r4,#26
strb r4,[r1,r3]
add r3,#1
b 1b
100:
pop {r3,r4,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* decrypt strings */
/******************************************************************/
/* r0 contains the address of the encrypted string1 */
/* r1 contains the address of the decrypted string */
/* r2 contains the key (1-25) */
decrypt:
push {r3,r4,lr} @ save registers
mov r3,#0 @ counter byte string 1
1:
ldrb r4,[r0,r3] @ load byte string 1
cmp r4,#0 @ zero final ?
streqb r4,[r1,r3]
moveq r0,r3
beq 100f
cmp r4,#65 @ < A ?
strltb r4,[r1,r3]
addlt r3,#1
blt 1b
cmp r4,#90 @ > Z
bgt 2f
sub r4,r2 @ substract key
cmp r4,#65 @ < A
addlt r4,#26
strb r4,[r1,r3]
add r3,#1
b 1b
2:
cmp r4,#97 @ < a ?
strltb r4,[r1,r3]
addlt r3,#1
blt 1b
cmp r4,#122 @ > z
strgtb r4,[r1,r3]
addgt r3,#1
bgt 1b
sub r4,r2 @ substract key
cmp r4,#97 @ < a
addlt r4,#26
strb r4,[r1,r3]
add r3,#1
b 1b
100:
pop {r3,r4,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return

View file

@ -0,0 +1,20 @@
(= rot (fn (L N)
(if
(and (<= 65 L) (>= 90 L))
(do
(= L (- L 65))
(= L (mod (+ N L) 26))
(= L (+ L 65)))
(and (<= 97 L) (>= 122 L))
(do
(= L (- L 97))
(= L (mod (+ N L) 26))
(= L (+ L 97))))
L))
(= caesar (fn (text (o shift))
(unless shift (= shift 13))
(= output (map [int _] (coerce text 'cons)))
(= output (map [rot _ shift] output))
(string output)
))

View file

@ -0,0 +1,2 @@
(caesar "The quick brown fox jumps over the lazy dog.")
"Gur dhvpx oebja sbk whzcf bire gur ynml qbt."

View file

@ -1,10 +1,13 @@
fun caesar(s, k, decode: false):
if decode:
k = 26 - k
char((ord(c) - 65 + k) mod 26 + 65) | c in uppercase(s) where 'a' <= c <= 'A').join()
result = ''
for i in s.uppercase() where 65 <= ord(i) <= 90:
result.push! char(ord(i) - 65 + k) mod 26 + 65
return result
let msg = "The quick brown fox jumped over the lazy dogs"
print msg
let message = "The quick brown fox jumped over the lazy dogs"
let encrypted = caesar(msg, 11)
let decrypted = caesar(enc, 11, decode: true)
let enc = caesar(msg, 11)
print(enc), :(caesar(enc, 11, decode: true))
print(message, encrypted, decrypted, sep: '\n')

View file

@ -0,0 +1,30 @@
# Caeser Cipher
# basic256 1.1.4.0
dec$ = ""
type$ = "cleartext "
input "If decrypting enter " + "<d> " + " -- else press enter > ",dec$ # it's a klooj I know...
input "Enter offset > ", iOffset
if dec$ = "d" then
iOffset = 26 - iOffset
type$ = "ciphertext "
end if
input "Enter " + type$ + "> ", str$
str$ = upper(str$) # a bit of a cheat really, however old school encryption is always upper case
len = length(str$)
for i = 1 to len
iTemp = asc(mid(str$,i,1))
if iTemp > 64 AND iTemp < 91 then
iTemp = ((iTemp - 65) + iOffset) % 26
print chr(iTemp + 65);
else
print chr(iTemp);
end if
next i

View file

@ -0,0 +1,217 @@
Author: Ettore Forigo | Hexwell
+ start the key input loop
[
memory: | c | 0 | cc | key |
^
, take one character of the key
:c : condition for further ifs
!= ' ' (subtract 32 (ascii for ' '))
--------------------------------
(testing for the condition deletes it so duplication is needed)
[>>+<+<-] duplicate
> |
[<+>-] |
> | :cc : copy of :c
[ if :cc
|
> | :key : already converted digits
|
[>++++++++++<-] | multiply by 10
> | |
[<+>-] | |
< | |
|
< | :cc
[-] | clear (making the loop an if)
] |
<< :c
[>>+<+<-] duplicate
> |
[<+>-] |
> | :cc
[ if :cc
---------------- | subtract 16 (difference between ascii for ' ' (already subtracted before) and ascii for '0'
| making '0' 0; '1' 1; etc to transform ascii to integer)
|
[>+<-] | move/add :cc to :key
] |
<< :c
]
memory: | 0 | 0 | 0 | key |
^
>>> :key
[<<<+>>>-] move key
memory: | key | 0 | 0 | 0 |
^
< ^
+ start the word input loop
[
memory: | key | 0 | c | 0 | cc |
^
, take one character of the word
:c : condition for further if
!= ' ' (subtract 32 (ascii for ' '))
--------------------------------
[>>+<+<-] duplicate
> |
[<+>-] |
> | :cc : copy of :c
[ if :cc
| subtract 65 (difference between ascii for ' ' (already subtracted before) and ascii for 'a'; making a 0; b 1; etc)
-----------------------------------------------------------------
|
<<<< | :key
|
[>>>>+<<<+<-] | add :key to :cc := :shifted
> | |
[<+>-] | |
|
| memory: | key | 0 | c | 0 | cc/shifted | 0 | 0 | 0 | 0 | 0 | divisor |
| ^
|
>>>>>>>>> | :divisor
++++++++++++++++++++++++++ | = 26
|
<<<<<< | :shifted
|
| memory: | shifted/remainder | 0 | 0 | 0 | 0 | 0 | divisor |
| ^
|
| shifted % divisor
[ | | while :remainder
| | |
| | | memory: | shifted | 0 | 0 | 0 | 0 | 0 | divisor | 0 |
| | | ^
| | |
[>>>>>>>+<<<<+<<<-] | | | duplicate :cshifted : copy of shifted
| | |
| | | memory: | 0 | 0 | 0 | shifted | 0 | 0 | divisor | cshifted |
| | | ^
>>>>>> | | | :divisor ^
| | |
[<<+>+>-] | | | duplicate
< | | | |
[>+<-] | | | |
< | | | | :cdiv : copy of divisor
| | |
| | | memory: | 0 | 0 | 0 | shifted | cdiv | 0 | divisor | cshifted |
| | | ^
| | |
| | | subtract :cdiv from :shifted until :shifted is 0
[ | | | | while :cdiv
< | | | | | :shifted
| | | | |
[<<+>+>-] | | | | | duplicate
< | | | | | |
[>+<-] | | | | | |
< | | | | | | :csh
| | | | |
| | | | | memory: | 0 | csh | 0 | shifted/remainder | cdiv | 0 | divisor | cshifted |
| | | | | ^
| | | | |
| | | | | subtract 1 from :shifted if not 0
[ | | | | | | if :csh
>>-<< | | | | | | | subtract 1 from :shifted
[-] | | | | | | | clear
] | | | | | | |
| | | | |
>>> | | | | | :cdiv
- | | | | | subtract 1
] | | | | |
| | |
| | |
| | | memory: | 0 | 0 | 0 | remainder | 0 | 0 | divisor | cshifted |
| | | ^
< | | | :remainder ^
| | |
[>+<<<<+>>>-] | | | duplicate
| | |
| | | memory: | remainder | 0 | 0 | 0 | crem | 0 | divisor | shifted/modulus |
| | | ^
> | | | :crem ^
| | |
| | | clean up modulus if a remainder is left
[ | | | if :crem
>>>[-]<<< | | | | clear :modulus
[-] | | | | clear
] | | | |
| | |
| | | if subtracting :cdiv from :shifted left a remainder we need to do continue subtracting;
| | | otherwise modulus is the modulus between :divisor and :shifted
| | |
<<<< | | | :remainder
] | | |
|
| memory: | 0 | 0 | 0 | 0 | 0 | 0 | divisor | modulus | 0 | cmod | eq26 |
| ^
|
>>>>>>> | :modulus
|
[>>+<+<-] | duplicate
> | |
[<+>-] | |
> | | :cmod : copy of :modulus
|
| memory: | 0 | 0 | 0 | 0 | 0 | 0 | divisor | modulus | 0 | cmod | eq26 |
| ^
|
-------------------------- | subtract 26
|
> | :eq26 : condition equal to 26
+ | add 1 (set true)
|
< | :cmod
[ | if :cmod not equal 26
>-< | | subtract 1 from :eq26 (set false)
[-] | | clear
] | |
|
> | :eq26
|
[ | if :eq26
<<<[-]>>> | | clear :modulus
[-] | | clear
] | |
|
| the modulus operation above gives 26 as a valid modulus; so this is a workaround for setting a
| modulus value of 26 to 0
|
<<<< |
[-] | clear :divisor
|
| memory: | c | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | modulus |
| ^
> | :modulus ^
[<<<<<<<+>>>>>>>-] | move :modulus
|
| memory: | c | 0 | modulus/cc | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| ^
<<<<<<< | :modulus/cc ^
|
| add 97 (ascii for 'a'; making 0 a; 1 b; etc)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
. | print
[-] | clear
] |
memory: | c | 0 | modulus/cc |
^
<< :c ^
]

View file

@ -0,0 +1 @@
10 abc

View file

@ -0,0 +1 @@
16 klm

View file

@ -1,6 +1,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define caesar(x) rot(13, x)
#define decaesar(x) rot(13, x)
@ -16,8 +17,11 @@ void rot(int c, char *str)
{
if (!isalpha(str[i]))
continue;
str[i] = alpha[isupper(str[i])][((int)(tolower(str[i])-'a')+c)%26];
if (isupper(str[i]))
str[i] = alpha[1][((int)(tolower(str[i]) - 'a') + c) % 26];
else
str[i] = alpha[0][((int)(tolower(str[i]) - 'a') + c) % 26];
}
}

View file

@ -0,0 +1,9 @@
(defun caesar-encipher (s k)
(map 'string #'(lambda (c) (z c k)) s))
(defun caesar-decipher (s k) (caesar-encipher s (- k)))
(defun z (h k &aux (c (char-code h))
(b (or (when (<= 97 c 122) 97)
(when (<= 65 c 90) 65))))
(if b (code-char (+ (mod (+ (- c b) k) 26) b)) h))

View file

@ -1,73 +1,75 @@
import system'routines.
import system'math.
import extensions.
import extensions'text.
import system'routines;
import system'math;
import extensions;
import extensions'text;
const Letters = "abcdefghijklmnopqrstuvwxyz".
const BigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
const TestText = "Pack my box with five dozen liquor jugs.".
const Key = 12.
const string Letters = "abcdefghijklmnopqrstuvwxyz";
const string BigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string TestText = "Pack my box with five dozen liquor jugs.";
const int Key = 12;
class Encrypting :: Enumerator
class Encrypting : Enumerator
{
object theKey.
object theEnumerator.
int theKey;
Enumerator theEnumerator;
constructor key:aKey text:aText
[
theKey := aKey.
theEnumerator := aText enumerator.
]
constructor(int key, string text)
{
theKey := key;
theEnumerator := text.enumerator();
}
bool next => theEnumerator.
bool next() => theEnumerator;
reset => theEnumerator.
reset() => theEnumerator;
enumerable => theEnumerator.
enumerable() => theEnumerator;
get
[
var aChar := theEnumerator get.
get()
{
var ch := theEnumerator.get();
var anIndex := Letters indexOf:aChar at:0.
var index := Letters.indexOf(0, ch);
if (-1 < anIndex)
[
^ Letters[(theKey+anIndex) mod:26]
];
[
anIndex := BigLetters indexOf:aChar at:0.
if (-1 < anIndex)
[
^ BigLetters[(theKey+anIndex) mod:26]
];
[
^ aChar
].
].
]
if (-1 < index)
{
^ Letters[(theKey+index).mod:26]
}
else
{
index := BigLetters.indexOf(0, ch);
if (-1 < index)
{
^ BigLetters[(theKey+index).mod:26]
}
else
{
^ ch
}
}
}
}
extension encryptOp
{
encrypt : aKey
= Encrypting key:aKey text:self; summarize(StringWriter new).
encrypt(key)
= new Encrypting(key, self).summarize(new StringWriter());
decrypt :aKey
= Encrypting key(26 - aKey) text:self; summarize(StringWriter new).
decrypt(key)
= new Encrypting(26 - key, self).summarize(new StringWriter());
}
public program =
[
console printLine("Original text :",TestText).
public program()
{
console.printLine("Original text :",TestText);
var anEncryptedText := TestText encrypt:Key.
var encryptedText := TestText.encrypt:Key;
console printLine("Encrypted text:",anEncryptedText).
console.printLine("Encrypted text:",encryptedText);
var aDecryptedText := anEncryptedText decrypt:Key.
var decryptedText := encryptedText.decrypt:Key;
console printLine("Decrypted text:",aDecryptedText).
console.printLine("Decrypted text:",decryptedText);
console readChar.
].
console.readChar()
}

View file

@ -1,20 +1,17 @@
import Data.Char (ord, chr, isUpper, isAlpha)
import Data.Bool (bool)
caesar, uncaesar :: Int -> String -> String
caesar = (<$>) . tr
caesar = fmap . tr
uncaesar = caesar . negate
tr :: Int -> Char -> Char
tr offset c
| isAlpha c = chr $ intAlpha + mod ((ord c - intAlpha) + offset) 26
| isAlpha c =
let i = ord $ bool 'a' 'A' (isUpper c)
in chr $ i + mod ((ord c - i) + offset) 26
| otherwise = c
where
intAlpha =
ord
(if isUpper c
then 'A'
else 'a')
main :: IO ()
main = mapM_ print [encoded, decoded]

View file

@ -0,0 +1,86 @@
MODULE Caesar EXPORTS Main;
IMPORT IO, IntSeq, Text;
EXCEPTION BadCharacter;
(* Used whenever message contains a non-alphabetic character. *)
PROCEDURE Encode(READONLY message: TEXT; numbers: IntSeq.T) RAISES { BadCharacter } =
(*
Converts upper or lower case letter to 0..25.
Raises a "BadCharacter" exception for non-alphabetic characters.
*)
VAR
c: CHAR;
v: INTEGER;
BEGIN
FOR i := 0 TO Text.Length(message) - 1 DO
c := Text.GetChar(message, i);
CASE c OF
| 'A'..'Z' => v := ORD(c) - ORD('A');
| 'a'..'z' => v := ORD(c) - ORD('a');
ELSE
RAISE BadCharacter;
END;
numbers.addhi(v);
END;
END Encode;
PROCEDURE Decode(READONLY numbers: IntSeq.T; VAR message: TEXT) =
(* converts numbers in 0..26 to lower case characters *)
BEGIN
FOR i := 0 TO numbers.size() - 1 DO
message := message & Text.FromChar(VAL(numbers.get(i) + ORD('a'), CHAR));
END;
END Decode;
PROCEDURE Crypt(numbers: IntSeq.T; key: INTEGER) =
(*
In the Caesar cipher, encryption and decryption are really the same;
one adds the key, the other subtracts it. We can view this as adding a positive
or nevative integer; the common task is adding an integer. We call this "Crypt".
*)
BEGIN
FOR i := 0 TO numbers.size() - 1 DO
numbers.put(i, (numbers.get(i) + key) MOD 26);
END;
END Crypt;
PROCEDURE Encrypt(numbers: IntSeq.T; key := 4) =
(*
Encrypts a message of numbers using the designated key.
The result is also stored in "numbers".
*)
BEGIN
Crypt(numbers, key);
END Encrypt;
PROCEDURE Decrypt(numbers: IntSeq.T; key := 4) =
(*
Decrypts a message of numbers using the designated key.
The result is also stored in "numbers".
*)
BEGIN
Crypt(numbers, -key);
END Decrypt;
VAR
message := "";
buffer := NEW(IntSeq.T).init(22); (* sequence of 22 int's *)
BEGIN
TRY
Encode("WhenCaesarSetOffToGaul", buffer);
EXCEPT BadCharacter =>
(*
This should never occur.
Try adding spaces to the above to see what happens.
*)
IO.Put("Encountered a bad character in the input; completing partial task\n");
END;
Encrypt(buffer);
Decrypt(buffer);
Decode(buffer, message);
IO.Put(message); IO.PutChar('\n');
END Caesar.

View file

@ -5,31 +5,6 @@ let isupper c =
c >= 'A' && c <= 'Z'
let rot x str =
let upchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
and lowchars = "abcdefghijklmnopqrstuvwxyz" in
let rec decal x =
if x < 0 then decal (x + 26) else x
in
let x = (decal x) mod 26 in
let decal_up = x - (int_of_char 'A')
and decal_low = x - (int_of_char 'a') in
let len = String.length str in
let res = String.create len in
for i = 0 to pred len do
let c = str.[i] in
if islower c then
let j = ((int_of_char c) + decal_low) mod 26 in
res.[i] <- lowchars.[j]
else if isupper c then
let j = ((int_of_char c) + decal_up) mod 26 in
res.[i] <- upchars.[j]
else
res.[i] <- c
done;
(res)
(* or in OCaml 4.00+:
let rot x =
let upchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
and lowchars = "abcdefghijklmnopqrstuvwxyz" in
let rec decal x =
@ -47,5 +22,4 @@ let rot x =
upchars.[j]
else
c
)
*)
) str

View file

@ -0,0 +1,23 @@
main =>
S = "All human beings are born free and equal in dignity and rights.",
println(S),
println(caesar(S,5)),
println(caesar(caesar(S,5),-5)),
nl.
caesar(String, N) = Cipher =>
Lower = [chr(I): I in 97..122],
Upper = [chr(I): I in 65..90],
M = create_map(Lower, Upper, N),
% If a char is not in a..zA..z then show it as it is.
Cipher := [M.get(C,C) : C in String].
create_map(Lower,Upper, N) = M =>
M = new_map(),
Len = Lower.length,
foreach(I in 1..Len)
II = (N+I) mod Len,
if II == 0 then II := Len end, % Adjust for 1 based
M.put(Upper[I],Upper[II]),
M.put(Lower[I],Lower[II])
end.

View file

@ -1,65 +1,82 @@
var arr:[Character]=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
func res(st:String,ar:[Character],x:Int,ro:String)->String{
var str2:[Character]=[]
for i in st.characters
{
for j in 0...25
{
if i==ar[j]
{
switch ro
{
case "right":
if(j+x<=25)
{
str2.append(ar[j+x])
break
}
else
{
str2.append(ar[j+x-26])
break
}
case "left":
if(j-x>=0)
{
str2.append(ar[j-x])
break
}
else
{
str2.append(ar[j-x+26])
break
}
default:
print("incorrect input for rotation direction")
}
}
}
}
return String(str2)
func usage(_ e:String) {
print("error: \(e)")
print("./caeser -e 19 a-secret-string")
print("./caeser -d 19 tskxvjxlskljafz")
}
var mssg:String="hi"
var x1:Int=5
var rot:String="right"
var rotstr:String=res(st:mssg,ar:arr,x:x1,ro:rot)
print(rotstr)
func charIsValid(_ c:Character) -> Bool {
return c.isASCII && ( c.isLowercase || 45 == c.asciiValue ) // '-' = 45
}
func charRotate(_ c:Character, _ by:Int) -> Character {
var cv:UInt8! = c.asciiValue
if 45 == cv { cv = 96 } // if '-', set it to 'a'-1
cv += UInt8(by)
if 122 < cv { cv -= 27 } // if larget than 'z', reduce by 27
if 96 == cv { cv = 45 } // restore '-'
return Character(UnicodeScalar(cv))
}
func caesar(_ enc:Bool, _ key:Int, _ word:String) -> String {
let r = enc ? key : 27 - key
func charRotateWithKey(_ c:Character) -> Character {
return charRotate(c,r)
}
return String(word.map(charRotateWithKey))
}
func main() {
var encrypt = true
if 4 != CommandLine.arguments.count {
return usage("caesar expects exactly three arguments")
}
switch ( CommandLine.arguments[1] ) {
case "-e":
encrypt = true
case "-d":
encrypt = false
default:
return usage("first argument must be -e (encrypt) or -d (decrypt)")
}
guard let key = Int(CommandLine.arguments[2]) else {
return usage("second argument not a number (must be in range 0-26)")
}
if key < 0 || 26 < key {
return usage("second argument not in range 0-26")
}
if !CommandLine.arguments[3].allSatisfy(charIsValid) {
return usage("third argument must only be lowercase ascii characters, or -")
}
let ans = caesar(encrypt,key,CommandLine.arguments[3])
print("\(ans)")
}
func test() {
if ( Character("a") != charRotate(Character("a"),0) ) {
print("Test Fail 1")
}
if ( Character("-") != charRotate(Character("-"),0) ) {
print("Test Fail 2")
}
if ( Character("-") != charRotate(Character("z"),1) ) {
print("Test Fail 3")
}
if ( Character("z") != charRotate(Character("-"),26)) {
print("Test Fail 4")
}
if ( "ihgmkzma" != caesar(true,8,"a-zecret") ) {
print("Test Fail 5")
}
if ( "a-zecret" != caesar(false,8,"ihgmkzma") ) {
print("Test Fail 6")
}
}
test()
main()

View file

@ -0,0 +1,31 @@
Module Module1
Function Encrypt(ch As Char, code As Integer) As Char
If Not Char.IsLetter(ch) Then
Return ch
End If
Dim offset = AscW(If(Char.IsUpper(ch), "A"c, "a"c))
Dim test = (AscW(ch) + code - offset) Mod 26 + offset
Return ChrW(test)
End Function
Function Encrypt(input As String, code As Integer) As String
Return New String(input.Select(Function(ch) Encrypt(ch, code)).ToArray())
End Function
Function Decrypt(input As String, code As Integer) As String
Return Encrypt(input, 26 - code)
End Function
Sub Main()
Dim str = "Pack my box with five dozen liquor jugs."
Console.WriteLine(str)
str = Encrypt(str, 5)
Console.WriteLine("Encrypted: {0}", str)
str = Decrypt(str, 5)
Console.WriteLine("Decrypted: {0}", str)
End Sub
End Module

View file

@ -0,0 +1,102 @@
# Author: Ettore Forigo - Hexwell
.intel_syntax noprefix
.text
.globl main
main:
.PROLOGUE:
push rbp
mov rbp, rsp
sub rsp, 32
mov QWORD PTR [rbp-32], rsi # argv
.BODY:
mov BYTE PTR [rbp-1], 0 # shift = 0
.I_LOOP_INIT:
mov BYTE PTR [rbp-2], 0 # i = 0
jmp .I_LOOP_CONDITION # I_LOOP_CONDITION
.I_LOOP_BODY:
movzx edx, BYTE PTR[rbp-1] # shift
mov eax, edx # shift
sal eax, 2 # shift << 2 == i * 4
add eax, edx # shift * 4 + shift = shift * 5
add eax, eax # shift * 5 + shift * 5 = shift * 10
mov ecx, eax # shift * 10
mov rax, QWORD PTR [rbp-32] # argv
add rax, 8 # argv + 1
mov rdx, QWORD PTR [rax] # argv[1]
movzx eax, BYTE PTR [rbp-2] # i
add rax, rdx # argv[1] + i
movzx eax, BYTE PTR [rax] # argv[1][i]
add eax, ecx # shift * 10 + argv[1][i]
sub eax, 48 # shift * 10 + argv[1][i] - '0'
mov BYTE PTR [rbp-1], al # shift = shift * 10 + argv[1][i] - '0'
.I_LOOP_INCREMENT:
movzx eax, BYTE PTR [rbp-2] # i
add eax, 1 # i + 1
mov BYTE PTR [rbp-2], al # i++
.I_LOOP_CONDITION:
mov rax, QWORD PTR [rbp-32] # argv
add rax, 8 # argv + 1
mov rax, QWORD PTR [rax] # argv[1]
movzx edx, BYTE PTR [rbp-2] # i
add rax, rdx # argv[1] + i
movzx rax, BYTE PTR [rax] # argv[1][i]
test al, al # argv[1][i]?
jne .I_LOOP_BODY # I_LOOP_BODY
.CAESAR_LOOP_INIT:
mov BYTE PTR [rbp-2], 0 # i = 0
jmp .CAESAR_LOOP_CONDITION # CAESAR_LOOP_CONDITION
.CAESAR_LOOP_BODY:
mov rax, QWORD PTR [rbp-32] # argv
add rax, 16 # argv + 2
mov rdx, QWORD PTR [rax] # argv[2]
movzx eax, BYTE PTR [rbp-2] # i
add rax, rdx # argv[2] + i
mov rbx, rax # argv[2] + i
movzx eax, BYTE PTR [rax] # argv[2][i]
cmp al, 32 # argv[2][i] == ' '
je .CAESAR_LOOP_INCREMENT # CAESAR_LOOP_INCREMENT
movzx edx, BYTE PTR [rbx] # argv[2][i]
mov ecx, edx # argv[2][i]
movzx edx, BYTE PTR [rbp-1] # shift
add edx, ecx # argv[2][i] + shift
sub edx, 97 # argv[2][i] + shift - 'a'
mov BYTE PTR [rbx], dl # argv[2][i] = argv[2][i] + shift - 'a'
movzx eax, BYTE PTR [rbx] # argv[2][i]
cmp al, 25 # argv[2][i] <=> 25
jle .CAESAR_RESTORE_ASCII # <= CAESAR_RESTORE_ASCII
movzx edx, BYTE PTR [rbx] # argv[2][i]
sub edx, 26 # argv[2][i] - 26
mov BYTE PTR [rbx], dl # argv[2][i] = argv[2][i] - 26
.CAESAR_RESTORE_ASCII:
movzx edx, BYTE PTR [rbx] # argv[2][i]
add edx, 97 # argv[2][i] + 'a'
mov BYTE PTR [rbx], dl # argv[2][i] = argv[2][i] + 'a'
.CAESAR_LOOP_INCREMENT:
movzx eax, BYTE PTR [rbp-2] # i
add eax, 1 # i + 1
mov BYTE PTR [rbp-2], al # i++
.CAESAR_LOOP_CONDITION:
mov rax, QWORD PTR [rbp-32] # argv
add rax, 16 # argv + 2
mov rdx, QWORD PTR [rax] # argv[2]
movzx eax, BYTE PTR [rbp-2] # i
add rax, rdx # argv[2] + i
movzx eax, BYTE PTR [rax] # argv[2][i]
test al, al # argv[2][i]?
jne .CAESAR_LOOP_BODY # CAESAR_LOOP_BODY
mov rax, QWORD PTR [rbp-32] # argv
add rax, 16 # argv + 2
mov rax, QWORD PTR [rax] # argv[2]
mov rdi, rax # argv[2]
call puts # puts(argv[2])
.RETURN:
mov eax, 0 # 0
leave
ret # return 0

View file

@ -0,0 +1,5 @@
$ gcc caesar.S -o caesar
$ ./caesar 10 abc
klm
$ ./caesar 16 klm
abc