crypto – BabyPhD CTF Team https://babyphd.net Nói chung đây là một khái niệm vô cùng trừu tượng Fri, 11 Mar 2016 10:50:26 +0000 en-US hourly 1 https://wordpress.org/?v=5.2.2 104079289 Basic concepts of Chinese Remainder Theorem with respect of RSA/AES https://babyphd.net/2016/03/11/basic-concepts-of-chinese-remainder-theorem-with-respect-of-rsaaes/ Fri, 11 Mar 2016 07:29:37 +0000 https://babyphd.net/?p=465 Continue reading Basic concepts of Chinese Remainder Theorem with respect of RSA/AES ]]>  

Chinese Remainder Theorem
=========================

Suppose are positive integers and coprime in pair. For any sequence of integers , there exists an integer x solving the following system of congruence equations:


There exists an unique modulo solution of the system of simultaneous congruences above:

in which:

**Example**:

Solve:
Therefore,

Hence, the solution of this simultaneous congruences is for all k are integers.

RSA using the Chinese remainder theorem
=======================================

In RSA scheme using the Chinese remainder theorem, the following values are precomputed and stored as a public key:

Therefore, we can compute the message from given ciphertext more effienctly as follow:

This scheme is more efficient than computing because these two modular exponentiations both use a smaller exponent and a smaller modulus.

**Proof:**

We know that:

Note that the exponents are reduced module p-1 and q-1. This can be done using Fermat’s little theorem because p and q.Then, we recombine the; that is, we find a number m such that:

Because of the Chinese Remainder Theorem (and because p and q are relatively prime), we can immediately deduce that:  which is exactly what we were trying to compute.

Now, the questions in your comments appear to be asking about the details of this recombination step. It is actually fairly easy to see the correctness of the algorithm. To make the last step work, we need to show that we have come up with a value m such that:

As for the the first criteria , well, that’s straight-forward; we know that , and , and so the smallest that m can be is , and the largest it can be is

As for the third criteria, that’s also straight-forward;

Now, is defined to be the number that, when multiplied by q modulo p, results in 1, or . Now, because the above equation is, in fact, computed modulo p, we can replace with 1, which gives us:

Program for secure communication
================================

My following program was written using Python language. It includes 4 main parts:

- Take user text input from the console and encrypt it using AES-128 using built-in library Crypto.Cipher

aes_encrypt

- Encrypt the AES key using RSA where prime p,q were generated
randomly with the length of 1024 bits

rsa_encrypt

- Decrypt the key

- Using the normal RSA function

def decrypt(self, c,d,n):
return pow(c,d,n)

 

- Using the CRT approach

 {frame="single"}
def decryptCRT(self,c,p,q,d,dp,dq,qi):
m1 = pow(c,dp,p)
m2 = pow(c,dq,q)
h = (qi*(m1-m2))%p
m = m2+ h*q
return m

rsa_decrypt

- Decrypt the message using AES128 decryption and print it on
the screen.

aes_decrypt

Report of execution time
========================

Each execution of the encryption and decryption functions is too short. Therefore, I measure the average time of total 1000 executions to compare between each method. To ensure that the time measurement does not affect the process execution, this program used an external call based on Python’s ’timer’ library to calculate the difference between start and end of each run in milliseconds.

 

self.end = time.time()
self.secs = self.end - self.start
self.msecs = self.secs * 1000 # millisecs
if self.verbose:
print 'Elapsed time: %f ms' % self.msecs

**Functions** **1000 times (second)** **Average (second)**
-------------------- ------------------------- ----------------------
AES128 encryption                 0.015999794                 0.000016
AES128 decryption                 0.014999866                 0.000015
RSA encryption                       0.254999876                 0.000255
RSA decryption                       39.37100005                 0.039371
RSA CRT decryption                 12.02799988                 0.012028
Total                                          51.68499947                 0.051685

Table time shows the execution time of RSA scheme is much larger than AES128 scheme. This result explains why RSA should being used in key exchange while parties encrypt their information using AES cryptosystem. Another significant result is that the RSA-CRT decryption method is approximately 3 times faster than normal RSA decryption.

Hope this article can bring cryptography motivation to some Math/IT students and players who were exhausted in enjoying CTF challenges, or at least it can be a good reference for somebody.

-chuymichxinhdep

Ref:

1<https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29>

2 <http://crypto.stackexchange.com/questions/2575/chinese-remainder-theorem-and-rsa>

**APPENDIX**

from Crypto.Cipher import AES
import math,random
from fractions import gcd
from random import randrange
from collections import namedtuple
from math import log
from binascii import hexlify, unhexlify
from timer import Timer

class RSA():
def __init__(self):
self.KeyPair = namedtuple('KeyPair', 'public private CRT')
self.Key = namedtuple('Key', 'exponent modulus')
self.KeyCRT = namedtuple('KeyCRT', 'p q')
def is_prime(self,n, k=30):
# Miller-Rabin Test
if n <= 3:
return n == 2 or n == 3
neg_one = n - 1

# write n-1 as 2^s*d where d is odd
s, d = 0, neg_one
while not d & 1:
s, d = s+1, d>>1
assert 2 ** s * d == neg_one and d & 1

for i in xrange(k):
a = randrange(2, neg_one)
x = pow(a, d, n)
if x in (1, neg_one):
continue
for r in xrange(1, s):
x = x ** 2 % n
if x == 1:
return False
if x == neg_one:
break
else:
return False
return True

def randprime(self,N=10**8):
p = 1
while not self.is_prime(p):
p = randrange(N)
return p

def multinv(self,modulus, value):
'''Multiplicative inverse in a given modulus
'''
# http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
x, lastx = 0, 1
a, b = modulus, value
while b:
a, q, b = b, a // b, a % b
x, lastx = lastx - q * x, x
result = (1 - lastx * modulus) // value
if result < 0:
result += modulus
assert 0 <= result < modulus and value * result % modulus == 1
return result

def keygen(self,N, public=None):
''' Generate public and private keys from primes up to N.
Optionally, specify the public key exponent (65537 is popular choice).
'''

# http://en.wikipedia.org/wiki/RSA
p = self.randprime(N)
q = self.randprime(N)
composite = p * q
totient = (p - 1) * (q - 1)
if public is None:
while True:
private = randrange(totient)
if gcd(private, totient) == 1:
break
public = self.multinv(totient, private)
else:
private = self.multinv(totient, public)
assert public * private % totient == gcd(public, totient) == gcd(private, totient) == 1
return self.KeyPair(self.Key(public, composite), self.Key(private, composite), self.KeyCRT(p, q))
def encrypt(self, m,e,n):
return pow(m,e,n)
def decrypt(self, c,d,n):
return pow(c,d,n)
def decryptCRT(self, c,p,q,d,dp,dq,qi):
m1 = pow(c,dp,p)
m2 = pow(c,dq,q)
h = (qi*(m1-m2))%p
m = m2+ h*q
return m
class PKCS7Encoder():
"""
Technique for padding a string as defined in RFC 2315, section 10.3,
note #2
"""
class InvalidBlockSizeError(Exception):
"""Raised for invalid block sizes"""
pass

def __init__(self, block_size=16):
if block_size < 2 or block_size > 255:
raise PKCS7Encoder.InvalidBlockSizeError('The block size must be ' \
'between 2 and 255, inclusive')
self.block_size = block_size

def encode(self, text):
text_length = len(text)
amount_to_pad = self.block_size - (text_length % self.block_size)
if amount_to_pad == 0:
amount_to_pad = self.block_size
pad = chr(amount_to_pad)
return text + pad * amount_to_pad

def decode(self, text):
pad = ord(text[-1])
return text[:-pad]
iv = "this is iv123456"
key = "this mus be a 16"

def AES_encrypt(iv,key,message):
obj = AES.new(key, AES.MODE_CBC, iv)
pkcs7 = PKCS7Encoder()
return obj.encrypt(pkcs7.encode(message)).encode("hex")

def AES_decrypt(iv,key,cipherText):
obj = AES.new(key, AES.MODE_CBC, iv)
pkcs7 = PKCS7Encoder()
return pkcs7.decode(obj.decrypt(cipherText.decode('hex')))

message = raw_input("Input message:")
with Timer() as t:
cipherText = AES_encrypt(iv,key,message)

print cipherText
print "AES encrypt: %s s" % t.secs

rsa = RSA()
pk,sk,primes = rsa.keygen(2**1024, 65537)

message = int(cipherText.encode("hex"),16)

with Timer() as t:

rsacipher = rsa.encrypt(message,pk.exponent, pk.modulus)

print rsacipher

print "RSA Encrypt: %s s" % t.secs
with Timer() as t:

messagersa = hex(rsa.decrypt(rsacipher, sk.exponent,sk.modulus)).replace("0x","").replace("L","").decode('hex')
print "RSA Decrypt: %s s" % t.secs
print messagersa
#Pre compute RSA CRT
p = primes.p
q = primes.q
dp = sk.exponent % (p-1)
dq = sk.exponent % (q-1)
qi = rsa.multinv(p,q)
#RSA-CRT Decryption

with Timer() as t:
for i in xrange(1):
messagersacrt = hex(rsa.decryptCRT(rsacipher,p,q,sk.exponent,dp,dq,qi)).replace("0x","").replace("L","").decode('hex')
print "RSA Decrypt CRT : %s s" % t.secs
print messagersacrt

with Timer() as t:
plainText = AES_decrypt(iv,key,messagersa)
print "Decrypted message:", plainText
print "AES decrypt: %s s" % t.secs
```

 

 

]]>
465
Introduction to Threshold signature scheme https://babyphd.net/2016/03/10/introduction-to-threshold-signature-scheme/ Thu, 10 Mar 2016 03:07:10 +0000 https://babyphd.net/?p=399 Continue reading Introduction to Threshold signature scheme ]]> THRESHOLD SIGNATURE SCHEME

  1. Introduction

Assuming there are 20 employees in a company, and if each employee has his or her own copy of the secret key then it is hard to assure on individuals due to compromise and machine break down. In the other hand, if there is a valid signature requires all 20 employees’ signature in the company then it will be very secure but not be easy to use. Therefore we can implement a scheme which requires only sign 5 or more out of 20 employees then it will be valid and that is exactly what a (5,20) threshold signature scheme tries to achieve. In addition, if a threat agent wants to compromise the system and obtain a message, he must compromise at least 5 people in the scheme and that is a harder thing to do compared to a traditional public scheme.

2. Threshold signature scheme

Threshold signature scheme is a branch of public key cryptography and multi-party computation particularly. In a k-out-of-n threshold crypto-system (k, n) where 1 < k ≤ n, we generate and split the secret decryption exponent d into n different pieces D1,…,Dn, which are then distributed privately to n parties. This enables:

• Knowledge of any k or more Di pieces makes D easily computable.

• Knowledge of any k- 1 or fewer Di pieces leaves D completely undetermined (in the sense that all its possible values are equally likely) [1]

2.1. Shared RSA Threshold Scheme

Similarly to traditional RSA, in shared RSA scheme, we have the public components are moduli N= pq and the encryption exponent e where e is co-prime to N. Additionally, both Boyd [2] and Frankel [3] independently proposed a simple and solution for distributed RSA. The decryption key d is additively shared amongst n parties where d = d1 + d2 + · · · + dn, and signing is simply calculated as follows:

s = md= md1· · · mdn (mod N), and each si = mdi (mod N) is called the partial signature or signature share.

Decryption is more complicated as there are more parties who get involved in the scheme. Assuming there are n parties and the prime factors of N remain unknown to every person. Each party Pi now only knows the tuple < pi, qi, di > and keeps it secret to any other parties, and they are also required to satisfy the four following conditions:

1. p is an unknown big prime number and

2. q is an unknown big prime number and

3. The unknown decryption exponent

4. And ed = 1 (mod φ(N )).

I am going to show a way to encrypt a message and decrypt a cipher text based on Discrete Logarithm Problem presented in [4].

  • Encryption: is similar to RSA :
  • Decryption: each party computes and then sends to all other parties. Each party knows all and then can recovers the original message (m) [5] as follow:

  • Advantages: Simple and easy to deploy.
  • Disadvantages: requires a trusted party and there is no verification process to avoid compromised party.

Proof:

Example:

Let p=47 and q=59, then N=pq=2773 and (p-1)(q-1)=2668. Assume e=17, we can calculate the value for d with 17d=1(mod 2668) or d=157. Each party Pi knows the tuple < pi, qi, di > : <13,19,61>, <11,23,53>, <23,17,43> respectively where p = 47 =13+11+23 ; q=59=19+23+17; and d=157=61+53+43. If the message is ready for the encryption is represent by m=9, then calculation of the ciphertext yields: .

Decipherment of the text requires knowledge of from all parties then it follows that:

M

=9, which is the original message.

2.2. Shamir’s Secret Sharing Scheme and Lagrange Coefficient

A trusted dealer has a secret s and chooses a large prime number p > n, the number of parties. Unless otherwise stated, all arithmetic operations are done modulo p. The dealer picks a1, …, at−1 uniformly random from Z𝑝 and defines P(x) = . Party Pi gets share si= P(i) privately from the dealer. To reconstruct the secret s, any t parties come together. They can recover the secret by solving the system of linear equations: . We can also denote .

Proof:

Larrange interpolation over with

Example:

Shamir’s threshold (3,4) over Z7:

Distribution: Dealer has secret s=4 and picks . Hence, polynomial . Dealer sends s1=4 to P1, s2=0 to P2, s3=6 to P1, s4=1 to P4.

Reconstruction: When P1, P3 and P4 come together, we have:

s =

4

2.3. Threshold ElGamal based on Shamir’s Secret Sharing Scheme

2.3.1 Threshold ElGamal scheme

Similarly to traditional ElGamal encryption scheme, in threshold ElGamal, we have the public components are (p,g,h) and private key in threshold environment. The dealer picks a1, …, at−1 uniformly random from Z𝑝 and defines P(x) = . Party Pi gets share si= P(i) privately from the dealer. This scheme of both construction and reconstruction of the secret is similar to the previous scheme based on Shamir’s Lagrange.

Example: public key (23, 5, 8) and private key = 6 in a (3,5)-threshold scheme [6].

  • Standard ElGamal encryption with message m and public key.

  • Decryption

Trusted dealer and every party can receive cipher = (B, c). Assume 3 parties {2,4,5} meet together to compute decryption share:

Trusted dealer computes using Shamir’s Lagrange: . Then compute

However, this scheme still requires a trusted third party (dealer) which is the most disadvantage when being compromised. Broadcasting partial secret information is used to avoid this problem using distributed key generation (DKG) as follow:

  • Each party acts as dealer picks a1, …, at−1 uniformly random from Z𝑝 and defines Pi(x) = . Party Pi sends si,j= Pi(j) privately to party Pj. All parties compute their secret key share: . And secret key .
  • To decrypt a given ciphertext (c1,c2). Let Q be any subgroup of size t, for example {P1,…,Pt}. Each party Pj of Q broadcast then compute . Thereafter, compute .

It is easy to prove that nobody can gain information about , however there is no verification if parties deviate from this scheme. In general, verifiable secret sharing ensures that even if the dealer is malicious there is a well-defined secret that the players can later reconstruct while in standard secret sharing, the dealer is assumed to be trusted. The concept of verifiable secret sharing (VSS) was first introduced in [7]. Therefore, I am going to show you two schemes to verify secret sharing: Feldman’s VSS scheme.

2.3.2 Threshold El-Gamal based on DKG and Feldman’s Verifiable Secret Sharing

Each party Pi picks ai,1, …, ai,t−1 uniformly random from Z𝑝 in given group G = <g> of order p and defines Pi(x) = . Party Pi shares si,j= Pi(j) privately to party Pj and broadcasts and . Hence all parties Pj can check own share: , compute key share: and compute verification key of Pi :

To decrypt a given ciphertext (c1,c2). Let Q be any subgroup of size t, for example {P1,…,Pt}. Each party Pj of Q broadcast similar to DKG scheme then compute . Use Zero knowledge proof to prove Thereafter, compute .[8]

  • Advantages: It does not require any trusted dealer and still can generate the public/private key pair efficiently with verification process.
  • Disadvantages: All parties’ identity need to be known to all other parties through every step.

4.Conclusion

Different applied schemes using threshold signature scheme is proposed in this report that includes: RSA shared secret, Shamir’s secret sharing, Elgamal threshold scheme, distributed key generation and verification as well as advantages and disadvantages of each scheme.

-cmxd

REFERENCES

[1] A. Shamir. How to share a secret. Communications of the ACM, 22, 612–613, 1979

[2] C. Boyd. Digital Multisignatures. Cryptography and Coding 1989. Institute of Mathematics and its application, IMA. 241–246, Clarendon Press, 1989

[3] Y. Frankel. A practical protocol for large group oriented networks. Advances in Cryptology – EUROCRYPT ’89, Springer-Verlag LNCS 434, 56–61, 1989.

[4] P. Paillier. Public key crypto-systems based on composite residue classes. Advances in Cryptography - EIROCRYPT ’99. Springer-Verlag LNCS 1070, pp. 72-83, 1996.

[5] H.L. Nguyen, RSA Threshold Cryptograph. University of Bristol, 2005.

[6] Björn Groneberg, Threshold Cryptography slides. University of Potsdam, 2013.

[7] Benny Chor, Shafi Goldwasser, Silvio Micali, Baruch Awerbuch. Verifiable secret sharing and achieving simultaneity in the presence of faults, SFCS '85 Proceedings of the 26th Annual Symposium on Foundations of Computer Science p. 383-395,1985.

[8] Dr. S.J.A. de Hoogh, Threshold Cryptography slides. TU/D, 2014.

]]>
399
Deciphering Ceasar basic concept https://babyphd.net/2016/03/08/deciphering-ceasar-basic-concept/ Tue, 08 Mar 2016 17:15:10 +0000 https://babyphd.net/?p=379 Continue reading Deciphering Ceasar basic concept ]]> Deciphering

 

Ciphertext: “VaqrprzoreoeratraWhyvhfraJnygreUbyynaqreqrgjrroebrefinaRqvguZnetbganne

NzfgreqnzNaarjvytenntzrrxbzraznnezbrgabtrrarragvwqwrovwbzn

oyvwiraBznmnyurgzbrvyvwxuroorabzNaarabtrracnnejrxraqnnegrubhqrafpuev

wsgRqvguSenaxvarraoevrsnnaTregehqAnhznaauhaiebrtrerohhezrvfwrvaSenaxs

hegnzZnva

The given ciphertext has only letters without space, punctuation or separated key, there are two classic cipher systems such as substitution cipher and transposition cipher which are known to be easy to attack by using frequency analysis or bruteforce techniques.

1. Bruteforce

Firstly, it is suggested that some sorts of simple substitution cipher has been used and Ceasar cipher is one of the most popular and simplest known encryption techniques. This encryption can be represented by aligning two alphabets; the ciphertext is the plain alphabet rotated left or right by some numbers of positions. It can be represented using modular arithmetic as well by first converting the letters into numbers such as A = 0, B = 1,..., Z = 25. Encryption of a letter x by a shift n can be described as E(x)=(x+n)mod 26 and the decryption is similarly D(x)=(x-n) mod 26. One way to break this is printing out all results with possible shifts of ciphertext by using bruteforce where the shift ranges from 1 to 26 (assuming they are only lower/uppercase letters in ASCII table). By using the Python program [1], there is a readable output as follow:

This result is in Dutch language and it means: “In December, bringing Juliusen Walter Hollander's two brothers Edith Margot to Amsterdam Anne would like to come but it must no be zero in some time with Grandma Omazal have tired of hard-to for Anne no no few weeks to keep writes Edith Frank Smash letter to Gertrud Naumann, their former neighbor in Frankfurtam Main”.

2. Frequency analysis

By analysing the frequency of ciphertext’s letters, and by knowing the expected distribution of letters in the original language of the plaintext, we can easily decipher substitution ciphertext by trying several combinations of mappings between ciphertext and plaintext letters based on the statistic. The letter frequency of the given ciphertext was derived by using the script [2] which shows the most frequently used letter: “R”. Given that the plaintext is in English, Dutch, German or Turkish, and there are many published frequency result extracted from common books such as: “etaoinsrhldcumfpgwybvkxjqz”, “enatirodslghvkmubpwjczfxy(ëéó)q”, “enisratdhulcgmobw fkzvüpäßjöyqx”, and “aeinrlıdkmuytsboüşzgçhğvcöpfjwxq” respectively[1].

In substituting the letters appeared the most in ciphertext by letters from those result above, I recognize the language of plaintext must be in Dutch. Because after replacing 2 most frequently used Dutch letter R, A in ciphertext with E, N respectively, I found out that the 3-letter-word “een(means “a” in English) appeared with high frequency and this word is one of the most popular Dutch words[2]. Keep replacing others based on the popular Dutch frequency letter with some guessing as described in [3], we get the final text which is similar to the first result.

3.Encryption algorithm improvements

Method 1:

This encryption can be improved by rotating left or right each letters by different numbers of positions. Firstly we convert the letters into numbers such as A = 0, B = 1,.., Z = 25. Encryption of a letter xi can be described as E(x_i )=(x_i+n*i)mod 26 and the decryption is similarly D(x_i )=(x_i-n*i) mod 26 where i is the letter’s position in plaintext or ciphertext. It will be difficult for attackers to use frequency analysis without knowing the encipher method and number n. An example of n=2 is described in [4].

Method 2:

This encryption can be improved by substituting each letters with a pseudo-random generated array of letters. Given an alphabet array consisting of uppercase and lowercase letters:

[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,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]

We shuffle this array by initializing a basic random generator with a seed number which can be the key or the time when this text was enciphered, then we have a Pseudo-random Array (PRA). We convert the letters into numbers such as A = 0, B = 1,.., Z = 25. Encryption of a letter x can be described as and the decryption is similarly where index is a function shows the letter’s position in array. The result consists of random uppercase or lowercase letters independent of plaintext. It will be difficult for attacker to use frequency analysis despite knowing the encipher method, however attackers can still bruteforce the seed if they know initial array’s order and a small value of seed was implemented. An example of seed=0xFFFFFFF is described in [5].

However, I've got a question for viewers: Do you think this kind of encryption seems tobe complex but it can still be beaten by simple substitution cipher analysis?

4. Conclusion

ROT13 is used in this encipher method with replaces a letter with other 13 letters after it in the alphabet. It can be easily broken even in a ciphertext-only scenario by using bruteforce and frequency analysis.

 

-cmxd

APPENDIX

[1]

import string
ciphertext = 'VaqrprzoreoeratraWhyvhfraJnygreUbyynaqreqrgjrroebrefinaRqvguZnetbganneNzfgreqnzNaarjvytenntzrrxbzraznnezbrgabtrrarragvwqwrovwbznoyvwiraBznmnyurgzbrvyvwxuroorabzNaarabtrracnnejrxraqnnegrubhqrafpuevwsgRqvguSenaxvarraoevrsnnaTregehqAnhznaauhaiebrtrerohhezrvfwrvaSenaxshegnzZnva'
for i in range(0,26):
    plaintext = ''
    for c in ciphertext:
        if c in string.uppercase:
            newpos = string.uppercase.find(c)+i
            if newpos>25 : newpos -= 26
            plaintext += string.uppercase[newpos]
        if c in string.lowercase:
            newpos = string.lowercase.find(c)+i
            if newpos>25 : newpos -= 26
            plaintext += string.lowercase[newpos]
    print "Shift:"+str(i)+" : "+plaintext

 

[2]

  1. # -*- coding: utf-8 -*-
    import collections, string
    cipher = 'VAQRPRZOREOERATRAWHYVHFRAJNYGREUBYYNAQREQRGJRROEBREFINARQVGUZNETBGANNENZFGREQNZNAARJVYTENNTZRRXBZRAZNNEZBRGABTRRARRAGVWQWROVWBZNOYVWIRABZNMNYURGZBRVYVWXUROORABZNAARABTRRACNNEJRXRAQNNEGRUBHQRAFPUEVWSGRQVGUSENAXVARRAOEVRSNNATREGEHQANHZNAAUHAIEBRTREROHHEZRVFWRVASENAXSHEGNZZNVA'
    dem = [[0, chr(i + ord('A'))] for i in range(26)]
    for ch in cipher:
        if ch not in string.uppercase:
            continue
        dem[ord(ch) - ord('A')][0] += 1
    count = {}
    dem.sort()
    dem = dem[::-1]
    print "Letter Frequency: ", dem
    for ch in [cipher[i:i+2] for i in xrange(0, len(cipher)-1)]:
        if (not count.get(ch)):
            count[ch]=1
        else:
            count[ch]+=1
    print "2 letters Frequency: ", collections.OrderedDict(sorted(count.items(), key=lambda t: t[1]))
    count = {}
    for ch in [cipher[i:i+3] for i in xrange(0, len(cipher)-2)]:
        if (not count.get(ch)):
            count[ch]=1
        else:
            count[ch]+=1
    print "3 letters Frequency: ",  collections.OrderedDict(sorted(count.items(), key=lambda t: t[1]))

     

[3]

  1. a = {}
    # #e n a t i r o d s l g h v k m u b p w j c z f x y (e e o) q DUTCH
    #e n a r m i t o d u b l j h g s k f w v c z p y x q
    a['R'] = 'E'
    a['A'] = 'N'
    a['N'] = 'A'
    a['E'] = 'R'
    a['Z'] = 'M'
    a['V'] = 'I'
    a['G'] = 'T'
    a['B'] = 'O'
    a['Q'] = 'D'
    a['O'] = 'B'
    a['H'] = 'U'
    a['Y'] = 'L'
    a['W'] = 'J'
    a['U'] = 'K'
    a['T'] = 'G'
    a['X'] = 'U'
    a['S'] = 'F'
    a['F'] = 'S'
    a['J'] = 'W'
    a['I'] = 'V'
    a['P'] = 'C'
    a['M'] = 'Z'
    a['C'] = 'P'
    plaintext = ''
    for ch in cipher:
        if ch in a.keys():
            plaintext = plaintext + a[ch]
        else:
            plaintext = plaintext + '*'
    print plaintext

     

[4]

  1. import string
    plaintext="IndecemberbrengenJuliusenWalterHollanderdetweebroersvanEdithMargotnaarAmsterdamAnnewilgraagmeekomenmaarmoetnogeeneentijdjebijomablijvenOmazalhetmoeilijkhebbenomAnnenogeenpaarwekendaartehoudenschrijftEdithFrankineenbriefaanGertrudNaumannhunvroegerebuurmeisjeinFrankfurtamMain"
    ciphertext=""
    for i in range(1,len(plaintext)+1):
        shift = (2*i%26)
        if plaintext[i-1] in string.uppercase:
            newpos = string.uppercase.find(plaintext[i-1])+shift
            if newpos>25 : newpos -= 26
            ciphertext += string.uppercase[newpos]
        elif plaintext[i-1] in string.lowercase:
            newpos = string.lowercase.find(plaintext[i-1])+shift
            if newpos>25 : newpos -= 26
            ciphertext += string.lowercase[newpos]
    print "Ciphertext: ", ciphertext
    #Decipher
    plaintext=""
    for i in range(1,len(ciphertext)+1):
        shift = (2*i%26)
        if ciphertext[i-1] in string.uppercase:
            newpos = string.uppercase.find(ciphertext[i-1])-shift
            if newpos<0 : newpos += 26
            plaintext += string.uppercase[newpos]
        elif ciphertext[i-1] in string.lowercase:
            newpos = string.lowercase.find(ciphertext[i-1])-shift
            if newpos<0 : newpos += 26
            plaintext += string.lowercase[newpos]
    print "Plaintext: ", plaintext

     

[5]

  1. import random
    def random_encipher(string,seed):
       random.seed(seed)
       alphabet = ["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","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"]
       random.shuffle(alphabet)
       ciphers = ""
       for letter in string:
        if ord(letter) >=97:
           index = ord(letter)-97
           cipher = alphabet[index]
           ciphers+=cipher
        else:
           index = ord(letter)-65
           cipher = alphabet[26+index]
           ciphers+=cipher
       return ciphers
    def random_decipher(string,seed):
       random.seed(seed)
       alphabet = ["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","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"]
       random.shuffle(alphabet)
       plaintext = ""
       for letter in string:
        index=alphabet.index(letter)
        if index >=26:
           plaintext += chr(65+index-26)
        else:
           plaintext += chr(97+index)
       return plaintext
    ciphertext= random_encipher("IndecemberbrengenJuliusenWalterHollanderdetweebroersvanEdithMargotnaarAmsterdamAnnewilgraagmeekomenmaarmoetnogeeneentijdjebijomablijvenOmazalhetmoeilijkhebbenomAnnenogeenpaarwekendaartehoudenschrijftEdithFrankineenbriefaanGertrudNaumannhunvroegerebuurmeisjeinFrankfurtamMain",0xFFFFFFF )
    print "Ciphertext: ", ciphertext
    print "Plaintext: ",random_decipher(ciphertext, 0xFFFFFFF )

     

  1. http://www.letterfrequency.org
  2. https://en.wiktionary.org/wiki/Wiktionary:Frequency_lists#Dutch
]]>
379