June 2018 Update

This commit is contained in:
Ingy döt Net 2018-06-22 20:57:24 +00:00
parent ba8067c3b7
commit 22f33d4004
5278 changed files with 84726 additions and 14379 deletions

View file

@ -0,0 +1,28 @@
100 :
110 REM VIGENERE CIPHER
120 :
200 REM SET-UP
210 K$ = "LEMON": PRINT "KEY: "; K$
220 PT$ = "ATTACK AT DAWN": PRINT "PLAIN TEXT: ";PT$
230 DEF FN MOD(A) = A - INT (A / 26) * 26
300 REM ENCODING
310 K = 1
320 FOR I = 1 TO LEN (PT$)
330 IF ASC ( MID$ (PT$,I,1)) < 65
OR ASC ( MID$ (PT$,I,1)) > 90 THEN NEXT I
340 TV = ASC ( MID$ (PT$,I,1)) - 65
350 KV = ASC ( MID$ (K$,K,1)) - 65
360 CT$ = CT$ + CHR$ ( FN MOD(TV + KV) + 65)
370 K = K + 1: IF K > LEN (K$) THEN K = 1
380 NEXT I
390 PRINT "CIPHER TEXT: ";CT$
400 REM DECODING
410 K = 1
420 FOR I = 1 TO LEN (CT$)
430 TV = ASC ( MID$ (CT$,I,1)) - 65
440 KV = ASC ( MID$ (K$,K,1)) - 65
450 T = TV - KV: IF T < 0 THEN T = T + 26
460 DT$ = DT$ + CHR$ (T + 65)
470 K = K + 1: IF K > LEN (K$) THEN K = 1
480 NEXT I
490 PRINT "DECRYPTED TEXT: ";DT$

View file

@ -0,0 +1,48 @@
import system'text.
import system'math.
import system'routines.
import extensions.
class VCipher
{
literal encrypt(LiteralValue txt, LiteralValue pw, IntNumber d)
[
var output := TextBuilder new.
int pwi := 0.
literal $pw := pw upperCase.
txt upperCase; forEach(:t)
[
if(t >= $65)
[
int tmp := t toInt - 65 + d * ($pw[pwi] toInt - 65).
if (tmp < 0)
[
tmp += 26
].
output write((65 + tmp mod:26) toChar).
pwi += 1.
if (pwi == $pw length) [ pwi := 0 ]
]
].
^ output literal
]
}
program =
[
var v := VCipher new.
var s0 := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!".
var pw := "VIGENERECIPHER".
console printLine(s0,'newLine,pw,'newLine).
var s1 := v encrypt(s0, pw, 1).
console printLine("Encrypted:",s1).
s1 := v encrypt(s1, "VIGENERECIPHER", -1).
console printLine("Decrypted:",s1).
console printLine("Press any key to continue..").
console readKey.
].

View file

@ -0,0 +1,30 @@
USING: arrays ascii formatting kernel math math.functions
math.order sequences ;
IN: rosetta-code.vigenere-cipher
: mult-pad ( key input -- x )
[ length ] bi@ 2dup < [ swap ] when / ceiling ;
: lengthen-pad ( key input -- rep-key input )
[ mult-pad ] 2keep [ <repetition> concat ] dip
[ length ] keep [ head ] dip ;
: normalize ( str -- only-upper-letters )
>upper [ LETTER? ] filter ;
: vigenere-encrypt ( key input -- ecrypted )
[ normalize ] bi@ lengthen-pad
[ [ CHAR: A - ] map ] bi@ [ + 26 mod CHAR: A + ] 2map ;
: vigenere-decrypt ( key input -- decrypted )
[ normalize ] bi@ lengthen-pad [ [ CHAR: A - ] map ] bi@
[ - 26 - abs 26 mod CHAR: A + ] 2map ;
: main ( -- )
"Vigenere cipher" dup
"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
2dup "Key: %s\nInput: %s\n" printf
vigenere-encrypt dup "Encrypted: %s\n" printf
vigenere-decrypt "Decrypted: %s\n" printf ;
MAIN: main

View file

@ -1,41 +1,46 @@
function encrypt(msg::ASCIIString, key::ASCIIString)
msg = uppercase(join(filter(isalpha, collect(msg))))
len = length(msg)
key = uppercase(join(filter(isalpha, collect(key))))
function encrypt(msg::AbstractString, key::AbstractString)
msg = uppercase(join(filter(isalpha, collect(msg))))
key = uppercase(join(filter(isalpha, collect(key))))
msglen = length(msg)
keylen = length(key)
if length(key) < len
key = (key^(div(len - length(key), length(key)) + 2))[1:len]
if keylen < msglen
key = repeat(key, div(msglen - keylen, keylen) + 2)[1:msglen]
end
enc = Array(Char, len)
enc = Vector{Char}(msglen)
for i=1:length(msg)
@inbounds for i in 1:length(msg)
enc[i] = Char((Int(msg[i]) + Int(key[i]) - 130) % 26 + 65)
end
join(enc)
return join(enc)
end
function decrypt(enc::ASCIIString, key::ASCIIString)
enc = uppercase(join(filter(isalpha, collect(enc))))
len = length(enc)
key = uppercase(join(filter(isalpha, collect(key))))
function decrypt(enc::AbstractString, key::AbstractString)
enc = uppercase(join(filter(isalpha, collect(enc))))
key = uppercase(join(filter(isalpha, collect(key))))
msglen = length(enc)
keylen = length(key)
if length(key) < len
key = (key^(div(len - length(key), length(key)) + 2))[1:len]
if keylen < msglen
key = repeat(key, div(msglen - keylen, keylen) + 2)[1:msglen]
end
msg = Array(Char, len)
msg = Vector{Char}(msglen)
for i=1:length(enc)
@inbounds for i in 1:length(enc)
msg[i] = Char((Int(enc[i]) - Int(key[i]) + 26) % 26 + 65)
end
join(msg)
return join(msg)
end
const msg = "Attack at dawn."
const messages = ("Attack at dawn.", "Don't attack.", "The war is over.")
const key = "LEMON"
println(encrypt(msg, key))
println(decrypt(encrypt(msg, key), key))
for msg in messages
enc = encrypt(msg, key)
dec = decrypt(enc, key)
println("Original: $msg\n -> encrypted: $enc\n -> decrypted: $dec")
end

View file

@ -2,18 +2,16 @@
@.1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
L=length(@.1)
do j=2 to L; jm=j-1; q=@.jm
@.j=substr(q, 2, L-1)left(q, 1)
@.j=substr(q, 2, L - 1)left(q, 1)
end /*j*/
cypher = space('WHOOP DE DOO NO BIG DEAL HERE OR THERE', 0)
oMsg = 'People solve problems by trial and error; judgement helps pick the trial.'
oMsgU = oMsg; upper oMsgU
cypher_= copies(cypher, length(oMsg) % length(cypher) )
say ' original text =' oMsg
xMsg=Ncypher(oMsgU)
say ' cyphered text =' xMsg
bMsg=Dcypher(xMsg)
say 're-cyphered text =' bMsg
say ' original text =' oMsg
xMsg= Ncypher(oMsgU); say ' cyphered text =' xMsg
bMsg= Dcypher(xMsg) ; say 're-cyphered text =' bMsg
exit
/*──────────────────────────────────────────────────────────────────────────────────────*/
Ncypher: parse arg x; nMsg=; #=1 /*unsupported char? ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/
@ -23,7 +21,7 @@ Ncypher: parse arg x; nMsg=; #=1 /*unsupported char? ↓↓↓↓
return nMsg
/*──────────────────────────────────────────────────────────────────────────────────────*/
Dcypher: parse arg x; dMsg=
do i=1 for length(x); j=pos(substr(cypher_, i, 1), @.1)
dMsg=dMsg || substr(@.1, pos( substr(x, i, 1), @.j), 1)
do i=1 for length(x); j=pos(substr(cypher_, i, 1), @.1)
dMsg=dMsg || substr(@.1, pos( substr(x, i, 1), @.j), 1 )
end /*j*/
return dMsg

View file

@ -2,28 +2,26 @@
@abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU
@.1 = @abcU || @abc'0123456789~`!@#$%^&*()_-+={}|[]\:;<>?,./" '''
L=length(@.1)
do j=2 to length(@.1); jm=j-1; q=@.jm
@.j=substr(q, 2, L-1)left(q, 1)
do j=2 to length(@.1); jm=j - 1; q=@.jm
@.j=substr(q, 2, L - 1)left(q, 1)
end /*j*/
cypher = space('WHOOP DE DOO NO BIG DEAL HERE OR THERE', 0)
oMsg = 'Making things easy is just knowing the shortcuts. --- Gerard J. Schildberger'
cypher_= copies(cypher, length(oMsg) % length(cypher) )
say ' original text =' oMsg
xMsg=Ncypher(oMsg)
say ' cyphered text =' xMsg
bMsg=Dcypher(xMsg)
say 're-cyphered text =' bMsg
say ' original text =' oMsg
xMsg= Ncypher(oMsg); say ' cyphered text =' xMsg
bMsg= Dcypher(xMsg); say 're-cyphered text =' bMsg
exit
/*──────────────────────────────────────────────────────────────────────────────────────*/
Ncypher: parse arg x; nMsg=; #=1 /*unsupported char? ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/
do i=1 for length(x); j=pos(substr(x,i,1), @.1); if j==0 then iterate
nMsg=nMsg || substr(@.j, pos( substr( cypher_, #, 1), @.1), 1); #=#+1
nMsg=nMsg || substr(@.j, pos( substr( cypher_, #, 1), @.1), 1); #=# + 1
end /*j*/
return nMsg
/*──────────────────────────────────────────────────────────────────────────────────────*/
Dcypher: parse arg x; dMsg=
do i=1 for length(x); j=pos(substr(cypher_, i, 1), @.1)
dMsg=dMsg || substr(@.1, pos( substr(x, i, 1), @.j), 1)
do i=1 for length(x); j=pos(substr(cypher_, i, 1), @.1)
dMsg=dMsg || substr(@.1, pos( substr(x, i, 1), @.j), 1 )
end /*j*/
return dMsg

View file

@ -0,0 +1,77 @@
Red [needs: 'view]
CRLF: copy "^M^/" ;; constant for 0D 0A line feed
;;------------------------------------
crypt: func ["function to en- or decrypt message from textarea tx1"
/decrypt "decrypting switch/refinement" ][
;;------------------------------------
;; when decrypting we have to remove the superflous newlines
;; and undo the base64 encoding first ...
txt: either decrypt [ ;; message to en- or decrypt
s: copy tx1/text
;; newline could be single 0a byte or crlf sequence when copied from clipboard...
debase replace/all s either find s CRLF [CRLF ] [ newline ] ""
] [
tx1/text ;; plaintext message
]
txt: to-binary txt ;; handle message as binary
key: to-binary key1/text ;; handle key also as binary
bin: copy either decrypt [ "" ][ #{} ] ;; buffer for output
code: copy #{} ;; temp field to collect utf8 bytes when decrypting
;; loop over length of binary! message ...
repeat pos length? txt [
k: to-integer key/(1 + modulo pos length? key) ;; get corresponding key byte
c: to-integer txt/:pos ;; get integer value from message byte at position pos
either decrypt [ ;; decrypting ?
c: modulo ( 256 + c - k ) 256 ;; compute original byte value
case [
;; byte starting with 11.... ( >= 192 dec ) is utf8 startbyte
;; byte starting with 10... ( >= 128 dec) is utf8 follow up byte , below is single ascii byte
( c >= 192 ) or ( c < 128 ) [ ;; starting utf8 sequence byte or below 128 normal ascii ?
;; append last code to buffer, maybe normal ascii or utf8 sequence...
if not empty? code [ append bin to-char code ] ;; save previous code first
code: append copy #{} c ;; start new code
]
true [ append code c ] ;; otherwise utf8 follow up byte, append to startbyte
]
][
append bin modulo ( c + k ) 256 ;; encrypting , simply collect binary bytes
]
] ;; close repeat loop
either decrypt [ ;; collect utf-8 characters
append bin to-char code ;; append last code
tx2/text: to-string bin ;; create valid utf8 string when decrypting
][ ;; base64 encoding of crypted binary to get readable text string...
s: enbase copy bin ;; base 64 is default
while [40 < length? s ] [ ;; insert newlines for better "readability"
s: skip s either head? s [40][41] ;; ... every 40 characters
insert s newline
]
tx2/text: head s ;; reset s pointing to head again
]
]
;----------------------------------------------------------
; start of program
;----------------------------------------------------------
view layout [title "vigenere cyphre" ;Define nice GUI :- )
;----------------------------------------------------------
backdrop silver ;; define window background colour
text "message:" pad 99x1 button "get-clip" [tx1/text: read-clipboard]
;; code in brackets will be executed, when button is clicked:
button "clear" [tx1/text: copy "" ] return
tx1: area 330x80 "" return
text 25x20 "Key:" key1: field 290x20 "secretkey" return
button "crypt" [crypt ] button "decrypt" [crypt/decrypt ]
button "swap" [tx1/text: copy tx2/text tx2/text: copy "" ] return
text "de-/encrypted message:" pad 50x1 button "copy clip" [ write-clipboard tx2/text]
button "clear" [tx2/text: copy "" ] return
tx2: area 330x100 return
pad 270x1 button "Quit " [quit]
]

View file

@ -0,0 +1,48 @@
# Project : Vigenère cipher
# Date : 2018/01/02
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
key = "LEMON"
plaintext = "ATTACK AT DAWN"
ciphertext = encrypt(plaintext, key)
see "key = "+ key + nl
see "plaintext = " + plaintext + nl
see "ciphertext = " + ciphertext + nl
see "decrypted = " + decrypt(ciphertext, key) + nl
func encrypt(plain, key)
o = ""
k = 0
plain = fnupper(plain)
key = fnupper(key)
for i = 1 to len(plain)
n = ascii(plain[i])
if n >= 65 and n <= 90
o = o + char(65 + (n + ascii(key[k+1])) % 26)
k = (k + 1) % len(key)
ok
next
return o
func decrypt(cipher, key)
o = ""
k = 0
cipher = fnupper(cipher)
key = fnupper(key)
for i = 1 to len(cipher)
n = ascii(cipher[i])
o = o + char(65 + (n + 26 - ascii(key[k+1])) % 26)
k = (k + 1) % len(key)
next
return o
func fnupper(a)
for aa = 1 to len(a)
c = ascii(a[aa])
if c >= 97 and c <= 122
a[aa] = char(c-32)
ok
next
return a

View file

@ -0,0 +1,34 @@
object Vigenere {
def encrypt(msg: String, key: String) : String = {
var result: String = ""
var j = 0
for (i <- 0 to msg.length - 1) {
val c = msg.charAt(i)
if (c >= 'A' && c <= 'Z') {
result += ((c + key.charAt(j) - 2 * 'A') % 26 + 'A').toChar
j = (j + 1) % key.length
}
}
return result
}
def decrypt(msg: String, key: String) : String = {
var result: String = ""
var j = 0
for (i <- 0 to msg.length - 1) {
val c = msg.charAt(i)
if (c >= 'A' && c <= 'Z') {
result += ((c - key.charAt(j) + 26) % 26 + 'A').toChar
j = (j + 1) % key.length
}
}
return result
}
}
println("Encrypt text ABC => " + Vigenere.encrypt("ABC", "KEY"))
println("Decrypt text KFA => " + Vigenere.decrypt("KFA", "KEY"))

View file

@ -0,0 +1,65 @@
Option Explicit
Sub test()
Dim Encryp As String
Encryp = Vigenere("Beware the Jabberwock, my son! The jaws that bite, the claws that catch!", "vigenerecipher", True)
Debug.Print "Encrypt:= """ & Encryp & """"
Debug.Print "Decrypt:= """ & Vigenere(Encryp, "vigenerecipher", False) & """"
End Sub
Private Function Vigenere(sWord As String, sKey As String, Enc As Boolean) As String
Dim bw() As Byte, bk() As Byte, i As Long, c As Long
Const sW As String = "ÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ"
Const sWo As String = "AAAAACEEEEIIIINOOOOOUUUUY"
Const A As Long = 65
Const N As Long = 26
c = Len(sKey)
i = Len(sWord)
sKey = Left(IIf(c < i, StrRept(sKey, (i / c) + 1), sKey), i)
sKey = StrConv(sKey, vbUpperCase) 'Upper case
sWord = StrConv(sWord, vbUpperCase)
sKey = StrReplace(sKey, sW, sWo) 'Replace accented characters
sWord = StrReplace(sWord, sW, sWo)
sKey = RemoveChars(sKey) 'Remove characters (numerics, spaces, comas, ...)
sWord = RemoveChars(sWord)
bk = CharToAscii(sKey) 'To work with Bytes instead of String
bw = CharToAscii(sWord)
For i = LBound(bw) To UBound(bw)
Vigenere = Vigenere & Chr((IIf(Enc, ((bw(i) - A) + (bk(i) - A)), ((bw(i) - A) - (bk(i) - A)) + N) Mod N) + A)
Next i
End Function
Private Function StrRept(s As String, N As Long) As String
Dim j As Long, c As String
For j = 1 To N
c = c & s
Next
StrRept = c
End Function
Private Function StrReplace(s As String, What As String, By As String) As String
Dim t() As String, u() As String, i As Long
t = SplitString(What)
u = SplitString(By)
StrReplace = s
For i = LBound(t) To UBound(t)
StrReplace = Replace(StrReplace, t(i), u(i))
Next i
End Function
Private Function SplitString(s As String) As String()
SplitString = Split(StrConv(s, vbUnicode), Chr(0))
End Function
Private Function RemoveChars(str As String) As String
Dim b() As Byte, i As Long
b = CharToAscii(str)
For i = LBound(b) To UBound(b)
If b(i) >= 65 And b(i) <= 90 Then RemoveChars = RemoveChars & Chr(b(i))
Next i
End Function
Private Function CharToAscii(s As String) As Byte()
CharToAscii = StrConv(s, vbFromUnicode)
End Function

View file

@ -0,0 +1,34 @@
'vigenere cypher
option explicit
const asca =65 'ascii(a)
function filter(s)
with new regexp
.pattern="[^A-Z]"
.global=1
filter=.replace(ucase(s),"")
end with
end function
function vigenere (s,k,sign)
dim s1,i,a,b
for i=0 to len(s)-1
a=asc(mid(s,i+1,1))-asca
b=sign * (asc(mid(k,(i mod len(k))+1,1))-asca)
s1=s1 & chr(((a+b+26) mod 26) +asca)
next
vigenere=s1
end function
function encrypt(s,k): encrypt=vigenere(s,k,1) :end function
function decrypt(s,k): decrypt=vigenere(s,k,-1) :end function
'test--------------------------
dim plaintext,filtered,key,encoded
key="VIGENERECYPHER"
plaintext = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
filtered= filter(plaintext)
wscript.echo filtered
encoded=encrypt(filtered,key)
wscript.echo encoded
wscript.echo decrypt(encoded,key)