Recent Entries 10
- pattern minor 112d agoVigenere cipher exercise in HaskellThis is my implementation using the dreadful `!!`: ``` import Data.Char (chr, ord, toUpper) -- A bit of self documentation help type Key = String type Msg = String key :: Key key = "TSTING" msg :: Msg msg = "I'm not even mad... This is impressive!" -- | Checks if character is valid for encoding isValid :: Char -> Bool isValid c = let cUp = toUpper c :: Char in 'A' Msg -> [Maybe Int] toIdx k m = map (flip mod keyN ) $ toIdx_ 0 m where keyN = length k :: Int toIdx_ :: Int -> Msg -> [Maybe Int] toIdx_ _ "" = [] toIdx_ acc (c:cs) | isValid c = Just acc : toIdx_ (acc + 1) cs | otherwise = Nothing : toIdx_ acc cs -- | Given 'key' & 'msg' generate a list of numbers representing -- the amount to shift 'msg' characters based on 'key' toShifts :: Key -> Msg -> [Int] toShifts k m = map toKey (toIdx k m) where kUp = map toUpper k :: Key toKey :: Maybe Int -> Int toKey Nothing = 0 toKey (Just x) = ord (kUp!!x) - ord 'A' -- | Given 'by' & 'c', shift the Char 'c' by amount 'by'. 'by' can be both -- positive & negative as well as 0. shift :: Int -> Char -> Char shift by c | isValid c && c >= 'a' = shift_ $ ord 'a' | isValid c && c >= 'A' = shift_ $ ord 'A' | otherwise = c where cONorm = ord (toUpper c) - ord 'A' :: Int azN = ord 'Z' - ord 'A' :: Int shift_ :: Int -> Char shift_ aO = chr $ aO + mod (by + cONorm) azN -- Encode & decode a message using the given key. vigenere, unVigenere :: Key -> Msg -> Msg vigenere k m = zipWith shift (toShifts k m) m unVigenere k m = zipWith shift (map negate $ toShifts k m) m ``` I found that the most "annoying" thing when coming from background such as `Python` is to be able to keep track of things, for example when figuring out how to convert valid characters into usable positions to be then mapped with the `key`. That thing took me half a day to figure out! How would you do it? Or is there some "standard" wa
- pattern minor 112d agoVigenere Cipher - Haskell ImplementationI'm reading 'Haskell Programming from First Principles' book written by Christopher Allen and Julie Moronuki. As part of the exercises, I'm supposed to implement encryption and decryption functions for Vigenere cipher. This is my implementation. I'm using recursion for every letter in the plain text. ``` shift :: (Int -> Int -> Int) -> Char -> Char -> Char -- shift applies a arithmetic function to given characters -- after converting it from ASCII value to Int -- This can be used to Encrypt or Decrypt the character shift f i k = let i' = ord i - 65 k' = ord k - 65 in chr $ ((f i' k') `mod` 26) + 65 crypt :: (Int -> Int -> Int) -> (String, Int) -> (String, Int) -> String -> String -- crypt applies given artithmetic function and does Vigenere encryption/decryption. -- This function moves forward on the string, encrypts the -- current char using corresponding char in key. It maintains -- current position of the string and key it is working on. When -- it encounters space, it skips the en(de)cryption and doen't move forward -- in the key. After encrypting the current char, it recursively calls -- itself by passing next positions in string to be encrypted along with -- position of key. crypt cryptFunc (words', wpos) (key, kpos) cipherText | length words' ' ' _ -> shift cryptFunc c $ key !! kpos kpos' = case c of ' ' -> kpos `mod` (length key) _ -> (kpos + 1) `mod` (length key) in crypt cryptFunc (words', wpos + 1) (key, kpos') (cipherText ++ [c']) encrypt :: [Char] -> [Char] -> [Char] encrypt i k = crypt (+) (i, 0) (k, 0) [] decrypt :: [Char] -> [Char] -> [Char] decrypt i k = crypt (-) (i, 0) (k, 0) [] -- input = "MEET AT DAWN" -- key = "ALLY" -- output = "MPPR AE OYWY" ``` Do you think the implementation is efficient and obvious way to do it? Please tell if there are any improvements I can do.
- pattern minor 112d agoCaesar and Vigenère ciphers in Haskell the simple wayThere are two ciphers, Caesar and Vigenère, both with an encoder and a decoder. Both work with spaces and can be passed any case (the output will be always lowercased, though). I'm a complete Haskell beginner and so my implementations are quite ugly and wordy. I'd welcome any help which would help me refactor the code, making it simpler, elegant and more readable. I think it could be possible to more reuse and reduce this code. I can't think of any way to do that, though. EDIT: Zeta's answer is great. I've refactored the following code according to his advice and added a new 'cipher' function which allows the user to create new ciphers. I raised a new question with the updated code, you can see it here. ``` import Data.Char (toLower, ord, chr) caesar :: Int -> String -> String caesar n s = unwords $ map (map chr) coded where coded = map (map helper) $ words s helper = (+) base . flip mod 26 . (+) n . flip (-) base . ord . toLower base = ord 'a' unCaesar :: Int -> String -> String unCaesar n s = unwords $ map (map chr) decoded where decoded = map (map helper) $ words s helper = (-) base . flip mod 26 . (+) n . (-) base . ord . toLower base = ord 'z' ``` I feel there should be a way to not handle the spaces like this, manually. Maybe zipping over a cycled key, somehow? ``` import Data.Char (toLower, ord, chr) vigenere :: String -> String -> String vigenere k s = unwords $ map (map chr) coded where coded = zipWith (zipWith helper) (words s) (words $ assign s 0) helper x y = base + mod (diff (toLower x) + diff (toLower y)) 26 base = ord 'a' diff = flip (-) base . ord assign str i | null str = "" | head str == ' ' = ' ' : assign (tail str) i | otherwise = (k !! i) : assign (tail str) (mod (i + 1) (length k)) unVigenere :: String -> String -> String unVigenere k s = unwords $ map (map chr) decoded where decoded = zipWith (zipWith helper) (words s) (words $ assign s 0) helper x y =
- pattern minor 112d agoBrute-force Vigenere Cipher using multiple threadsI'm trying to brute force a Vigenere Cipher knowing only that the key length is `5+` characters and that the decrypted text has the word `Hello, Andi`. So I wrote this small Java program that tries to brute-force the key through a given numbers of threads and nested while loops. Run.java (main class) ``` package vignere; import java.io.IOException; public class Run { public static void main(String[] args) throws IOException { //number of threads you have and encrypted text file Brute brute = new Brute(4, "41259.txt.enc"); Thread t1 = new Thread() { @Override public void run() { try { brute.bruteF_thread(1); } catch (IOException e) { e.printStackTrace(); } } }; Thread t2 = new Thread() { @Override public void run() { try { brute.bruteF_thread(2); } catch (IOException e) { e.printStackTrace(); } } }; Thread t3 = new Thread() { @Override public void run() { try { brute.bruteF_thread(3); } catch (IOException e) { e.printStackTrace(); } } }; Thread t4 = new Thread() { @Override public void run() { try { brute.bruteF_thread(4); } catch (IOException e) { e.printStackTrace(); } } }; t1.start(); t2.start(); t3.start(); t4.start(); try { t1.join(); t2.join(); t3.join(); t4.join(); } catch (Exception e) { e.printStackTrace(); } } } ``` And the class that handles the brute-force attack B
- pattern minor 112d agoVigenere cipher breakerI am a relative newbie to C++. I recently finished a command line program which cracks Vigenere encoded messages from a file by testing each word in the dictionary. I have never had a tutor/teacher for C++, so I wanted to make sure that I don't develop any bad habits. Main.cpp: ``` #include #include #include #include #include "Alphanumeric.h" //turns characters into numerical equivalents #include "Vigenere.h" //Vigenere Functions #include #ifdef __APPLE__ #define DICTPATH "/usr/share/dict/words" #endif int main(int argc, char* argv[]) { std::cout results; while (std::getline(dictionary, str)) { float total = 0; float frequency[26] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; std::cout results; std::string keyword = argv[3]; while (std::getline(dictionary, str)) { std::cout << "key:"; std::cout << str << std::endl; std::string result = Vigenere::DecryptVigenere(plain, str); if (result.find(keyword) != std::string::npos) { std::cout << "RESULT FOUND" << std::endl; results.push_back("Using " + str); results.push_back(result); } } std::cout << "*************RESULTS*************" << std::endl; for (std::string s : results) { std::cout << s << std::endl; } std::cout << "dictionary attack complete!!!" << std::endl; } return 0; } ``` Vigenere.h: ``` #ifndef VIGENERE_H_ #define VIGENERE_H_ namespace Vigenere { std::string DecryptVigenere(std::string ciphertext, std::string key); std::string EncryptVigenere(std::string plaintext, std::string key); } #endif /* VIGENERE_H_ */ ``` Vigenere.cpp: ``` #include #include "Vigenere.h" #include "Alphanumeric.h" std::string Vigenere::DecryptVigenere(std::string ciphertext, std::string key) { std::string answer; for (int i = 0; i < ciphertext.length(); i++) {
- pattern minor 112d agoVigenere cipher in HaskellI implemented the Vigenere cipher in haskell as a part of exercises for Haskell programming from first principles. Though the code isn't all that long, I feel it could use some refactoring to simplify things (I feel the code I wrote is ugly). One caveat: string inputs should all be in uppercase. The `vigenere` function should be applied like so: ``` vignere "ALLY" "MEET AT DAWN" ``` which will create the output: ``` "MPPRAEOYWY" ``` As it stands, here's the code I implemented: ``` import Data.Char -- exercise chapter 11 encode :: Char -> Int encode x = ord x - ord 'A' decode :: Int -> Char decode x = chr (x + ord 'A') shift :: (Int -> Int -> Int) -> Int -> Char -> Char shift f x ch = decode $ f (encode ch) x `mod` 26 rightShift :: Int -> Char -> Char rightShift = shift (+) leftShift :: Int -> Char -> Char leftShift = shift (-) encodeString :: String -> [Int] encodeString str = map encode str type Secret = String type PlainText = String type CipherText = String vignereString :: Secret -> PlainText -> String vignereString secret plain = take len $ cycle secret where len = length $ concat $ words plain vignereCode :: Secret -> PlainText -> [Int] vignereCode secret plain = encodeString $ vignereString secret plain vignere :: Secret -> PlainText -> CipherText vignere secret plain = zipWith rightShift code plainNoSpace where code = vignereCode secret plain plainNoSpace = concat $ words plain unvignere :: Secret -> CipherText -> PlainText unvignere secret cipher = zipWith leftShift code cipherNoSpace where code = vignereCode secret cipher cipherNoSpace = concat $ words cipher ```
- pattern minor 112d agoVigenère cipher in PythonOver the last year I have been programming on my own, mostly in Python. I haven't had any formal education, though I have followed some online instructions, and have been making things that interest me. One of those things is my Vigenère encrypter. I've made a few versions of it, and I would appreciate feedback on my latest version. Such as, does it follow somewhat of a good design pattern for these things? How would it perform under heavy load? If I can provide any additional information, please ask and I won't hesitate to do so. This is my code: ``` from os import system #characters to numbers table dictDown = {'|':0,'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8, 'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16, 'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24, 'y':25,'z':26,'.':27,',':28,"'":29,'!':30,':':31,'1':32, '2':33,'3':34,'4':35,'5':36,'6':37,'7':38,'8':39,'9':40, '0':41,'=':42,'-':43,'"':44,'+':45,'[':46,'_':47,'(':48, ')':49,' ':50,'?':51,'\n':52,'@':53,'#':54,'/':55,'%':56, '^':57,'*':58,']':59,'{':60,'}':61,'A':62,'B':63,'C':64, 'D':65,'E':66,'F':67,'G':68,'H':69,'I':70,'J':71,'K':72, 'L':73,'M':74,'N':75,'O':76,'P':77,'Q':78,'R':79,'S':80, 'T':81,'U':82,'V':83,'W':84,'X':85,'Y':86,'Z':87,'':89,';':90} #numbers to characters table dictUp = {0:'|',1:'a',2:'b',3:'c',4:'d',5:'e',6:'f',7:'g',8:'h', 9:'i',10:'j',11:'k',12:'l',13:'m',14:'n',15:'o',16:'p', 17:'q',18:'r',19:'s',20:'t',21:'u',22:'v',23:'w',24:'x', 25:'y',26:'z',27:'.',28:',',29:"'",30:'!',31:':',32:'1', 33:'2',34:'3',35:'4',36:'5',37:'6',38:'7',39:'8',40:'9', 41:'0',42:'=',43:'-',44:'"',45:'+',46:'[',47:'_',48:'(', 49:')',50:' ',51:'?',52:'\n',53:'@',54:'#',55:'/',56:'%', 57:'^',58:'*',59:']',60:'{',61:'}',62:'A',63:'B',64:'C', 65:'D',66:'E',67:'F',68:'G',69:'H',70:'I',71:'J',72:'K', 73:'L',74:'M',75:'N',76:'O',7
- pattern minor 112d agoPlaying around with Vigenere and Caesar cipher - Java command line encryption programI came along these two ciphers in my cryptography book and though I'd implement them just for fun. After that I went on developing a cipher based on these two that minimize the weakness of each cipher alone. I would appreciate your expert opinions on it and if it would be possible to crypt-analyse. ``` import java.util.*; import java.io.*; class CaesarCipher{ static String encrypt(String s, int key){ List arr = Arrays.asList('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'); StringBuilder str = new StringBuilder(); int index; for(int i = 0; i arr = Arrays.asList('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',' ','0','1','2','3','4','5','6','7','8','9'); Random rand = new Random(h); StringBuilder str = new StringBuilder(); int index1, index2; int hash = h; String key = k; for(int i = 0; i arr = Arrays.asList('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',' ','0','1','2','3','4','5','6','7','8','9'); Random rand = new Random(h); StringBuilder str = new StringBuilder(); int index1, index2; int hash = h; String key = k; String input = buff.readLine(); int count = 0; while(input != null){ for(int i = 0; i arr = Arrays.asList('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',' ','0','1','2','3','4','5','6','7','8','9'); Random rand = new Random(h); StringBuilder str = new StringBuilder(); int index1, index2; int hash = h; String key = k; for(int i = 0; i " + arr.get((index1 + (arr.size() - index2) )% arr.size())); } } return str.toString(); } static String decryptFile(BufferedReader buff, String k,int h) throws IOException{ List arr = Arrays.asList('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',' ','0','1','2','3','4','5','6','7','8','9'); Random rand = new Random(h); StringBuilder str
- pattern minor 112d agoA small custom encryption / decryption scriptI have made a small script for encrypting data. Now I'm wondering how efficient it is for normal users who aren't programmers and for people who are programmers. I mean if you don't have this script there is no way to find out what the text is right? ``` function cipher(message, action) { var text = message; var encrypted = ""; for(var i = 0; i < text.length; i++) { var ASCII = text[i].charCodeAt(0); var n = null; if(i % 2 == 0) { n = action == 'encrypt' ? ASCII + 4 : ASCII - 4; } else if(i % 2 == 1) { n = action == 'encrypt' ? ASCII + 7 : ASCII - 7; } var s = String.fromCharCode(n); encrypted += s;; } return encrypted; } console.log(cipher("Hello World", 'encrypt')) ``` If you were to make it more secure, what would you add? I was thinking of a complete custom random mapping for each letter but retrieving it after decryption is something I can't figure out yet.
- pattern minor 112d agoEncryption and decryption using alphabetic shiftsMy first piece of code encrypts text by moving each letter in the string 5 letters across in the alphabet. ``` encrypt = input('Enter text to encrypt : ') encrypt = encrypt.lower().replace(" ", "") for i in encrypt: print(chr(ord(i) + 5)) decrypt = input('Enter text to decrypt : ') decrypt = decrypt.lower().replace(" ", "") for i in decrypt: print(chr(ord(i) - 5)) ``` The output of this code if I enter 'hello' would be 'mjqqt'. To decrypt, I do the reverse, I move each letter 5 letters down the alphabet. Below is my second piece of code that encrypts text against a code word. For example... If I had 'abc' for the codeword and 'bcd' for the text to encrypt. Then: (a + b = 1 + 2) and this is repeated for each letter in the two words. The output of having my codeword as 'abc' and the word to encrypt and 'bcd' would be 'ceg'. ``` codeword = input('Enter codeword : ') codeword = codeword.replace(" ", "") encrypt = input('Enter text to encrypt : ') encrypt = encrypt.replace(" ", "") j = 0 for i in codeword: print(chr(ord(encrypt[j])+ ord(codeword[j])-96)) j+=1 ```