顯示具有 密碼學 標籤的文章。 顯示所有文章
顯示具有 密碼學 標籤的文章。 顯示所有文章

2015年11月29日 星期日

RSA加密法 & C 程式實作 & openssl 產生key

一、簡介:
  RSA是一種非對稱加密方式,使用者利用公鑰加密,或是使用私鑰解密。使用的數字通常很大(目前為1024 bit以上)。

二、流程:
  1. 產生鑰匙:
    A. 取兩質數p和q,並另N = p * q
    B. 設定 r 為(p - 1) * (q - 1)的公倍數。如:r = (p - 1) * (q - 1)
    C. 找一個e與r互質(且小於r)
    D. 找出e在mod r下的乘法反元素d  (e * d mod r = 1)
    E. (e, N)為公鑰;(d, N)則為私鑰

  2. 加密:
    密文 = (明文)e mod N
  3. 解密:
    明文 = (密文)d mod N

三、實作:
  1. 產生鑰匙: 利用openssl可以產生鑰匙
   
$openssl genrsa -out <file>.pem <key bit>

   
$openssl rsa -text -in <file>.pem
(轉為可讀的形式)
產生的key:
modulus即為N
publicExponent即為e
Private-Key即為d
也就是,使用(publicExponent, modulus)加密;使用(Private-Key, modulus)解密
最下面RSA private key為decode前的樣子(pem格式)

  2. 程式碼完全參照參考網址:(除了)
http://www.codedata.com.tw/social-coding/rsa-c-implementation/
(除了power有改變)

#include <stdio.h>
#include <assert.h>
#include <stdint.h>


#define BigInt uint64_t


BigInt newBigInt(char *str) {
  return atoi(str);
}

char tempStr[1025];

char *big2str(BigInt a) {
  sprintf(tempStr, "%lld", a);
  return tempStr;
}


BigInt mul(BigInt a, BigInt b) {
  return a*b;
}


BigInt div(BigInt a, BigInt b) {
  return a/b;
}


BigInt mod(BigInt a, BigInt n) {
  return a%n;
}



BigInt inv(BigInt e, BigInt r) {
  BigInt d;
  for (d=2; d<r; d++) {
    BigInt ed = mul(e, d); // re = (e*d) % r;
    BigInt re = mod(ed,r);
    if (re == 1) {
      printf("e=%lld d=%lld r=%lld (e*d) mod r=%lld\n", e, d, r, re);
      return d;
    }
  }
  assert(0);
}




BigInt Encrypt::power(BigInt a, BigInt k, BigInt N) {
    BigInt l_out = 1;



    while (k != 0)
    {



        if (k & 0x01)
        {
            l_out *= a;

            l_out = mod(l_out, N);
        }
        a *= a;
        a = mod(a, N);
        k = k >> 1;
    }
    return l_out;
}



int main() {
  BigInt p = newBigInt("2213"), q = newBigInt("2663");
  BigInt N = mul(p, q);
  BigInt r = mul(p-1, q-1);
  printf("N=%s r=%s\n", big2str(N), big2str(r));
  BigInt e = newBigInt("4723");
  BigInt d = inv(e, r);
  BigInt m = newBigInt("3320");
  printf("m=%s\n", big2str(m));
  BigInt c = power(m, e, N);
  printf("c=%s\n", big2str(c));
  BigInt m2 = power(c, d, N);
  printf("m2=%s\n", big2str(m2));
}


ref:
http://www.codedata.com.tw/social-coding/rsa-c-implementation/


2015年3月12日 星期四

Cryptography and Network Security-ch8

Ch8. Encipherment using modern symmetric-key cipher

5 mode to used with modern block cipher:
1.  Electronic Codebook (ECB):每個block單獨去加密
   加密:


   解密:


2. Cipher Block Chaining (CBC):將加密後的block和下一次的plaintext做XOR再加密(第一組需要initial vector)

加密:

解密:


3. Cipher Feedback (CFB):對shift register加密,加密後再和plaintext做XOR,得到的ciphertext再傳到下一個shift register

 加密:



4. Output Feedback(OFB):和CFB類似,但是傳到下一個block的是shift register加密後的temporary register

 加密:


5. Counter (CTR):直接利用counter加密,再和plaintext做XOR
 加密:



● mode 3, 4, 5 plaintext 中一個bit計算完及可以傳送這個bit,因此類似stream cipher
● ciphertext stealing:最後兩個block可以交換順序計算,進而避免最後一個block因位數不足做padding(也就是不需要做padding)
  在ECB mode下:
    X = Ek(PN-1)              → CN = headm(X)
    Y = PN | tailn-m(X)    → CN-1 = EK(Y)

  在CBC mode下:
    U = PN-1 + CN-2      →  X = Ek(U)     →  CN = headm(X)
    V = PN | padn-m(0)   → Y = X + V      → CN-1 = Ek(Y)

ref: wiki
http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_.28ECB.29

2015年1月26日 星期一

Cryptography and Network Security-ch7

Ch7 Advanced Encryption Standard

●3 version
1. AES 128(10 round, cipher key:128 bit)
2. AES 192(12 round, cipher key:192 bit)
3. AES 256(14 round, cipher key:256 bit)
●steps
1. Pre-round
    和key做XOR
2. Subbyte(Substation)
    
3. Shiftrow(Permutation)
  每個row做left shift 
 Row1: x
 Row2: 1 byte
 Row3: 2 byte
 Row4: 3 byte
4. Mix column 
 每個column獨立做(column乘constant matrix)
 最後一個column不做
5. Add round key
 每個column獨立做, plaintext 和 roundkey 做 XOR
6. 2, 3, 4, 5為一個round 依照不同version 做不同round
AES總流程圖
AES每個round的流程圖

● key expansion

1. AES 128:每個round需要4個word(wi, wi+1, wi+2, wi+3)
  (1). pre-round:w0, w1, w2, w3 為cipher key
  (2). 當i mod 4 = 0:
    wi = t + wi-4
    t = Sub(Rot(wi-1)) + Rcon[i/4]
  (3). 當i mod 4 ≠ 0:
    wi = wi-1 + wi-4
AES key產生圖

2. AES 192:每次產生6個word(wi, wi+1, wi+2, wi+3, wi+4, wi+5)
  和AES 128同,但4均改為6
  (wi = t + wi-6)
  ( wi = wi-1 + wi-6)
3. AES 256:每次產生8個word(wi, wi+1, wi+2, wi+3, wi+4, wi+5, wi+6, wi+7)
  (1). pre-round:w0, w1, w2, w3 為cipher key
  (2). 當i mod 8 = 0:
    wi = t + wi-8
    t = Sub(Rot(wi-1)) + Rcon
  (3). 當i mod 4 = 0, 且i mod 8 ≠ 0:
    wi = SubWord(wi-1) + wi-8
  (4). 當i mod 8 ≠ 0:
    wi = wi-1 + wi-8



2015年1月24日 星期六

Cryptography and Network Security-ch6

Chapter6 data encryption standard (DES)

●steps:
  1. Initial permutation 
  2. 右半Feistal cipher
       (1).expansion P-box  (32->48)
       (2).和round key XOR (48)
       (3).S-Boxes.               (48)
       (4).straight P-Box.      (48->32)
  3. 左半和右半XOR, 右半仍維持step2前的樣子
  4. swap (最後一個round不要)
  5. 重複step2, 3, 4(2, 3, 4為一個round, DES 跑16 round)
  6. final permutation
DES 完整程序圖
DES中的一個round
每個round中的Feistal cipher




●key gen
1. Key input
2. Parity drop
3. Shift left.     4. Shift left.  (1, 2, 9, 16 round: 1 bit, else: 2 bit)
5. Compression P-Box
重複step 3,4,5(3, 4, 5為一個round, DES 跑16 round)

DES gen key


●DES weakness
1. Weakness in key:
(1). Weak key: 一個weak key產生16個相同的subkey。這會使得plain-text加密兩次會產生plain-text
    Ek(Ek(P)) = P
(2). Semi weak key:一個semi-weak key會產生兩個不同subkey,每個subkey個會出現8次,稱這2個key為pair,使用這兩個subkey去加密會使plain-text 和cipher-text一樣。
    Ek1(Ek2(P)) = P
(3). Possible weak key:一個possible weak key會產生4個相同的weak key(subkey)。

2. Key complement 
C = E(P, K)
/C = E(/P, K)

3. Double DES
可以用meet in the middle attack


2014年12月21日 星期日

Cryptography and Network Security-Ch5

Chapter 5 Introduction to Modern Symmetric-key Ciphers

5.1 Modern Block Cipher
●modern block cipher分為兩種:transposition cipher 和 substitution cipher
  ○transposition cipher:key長度為⌈log2 n!⌉  bit
     (n!種對應)
  ○substitution cipher:key長度為⌈log2 (2n)!⌉ bit
     (2n!種對應)

●P-boxes:transposes bits
  ○Straight P-box:input bit = output bit
  ○Compression P-box:input bit > output bit
  ○Expansion P-box:input bit < output bit
     只有Straight P-box為可逆

e.g.
input: a b c d e f g h
P-box: [4 1 2 3 6 7 8 5]
output: d a b c f g h e
  ○invert P-boxes:
     1. 加index
     2. 將內容和index交換
     3.以index做sort

e.g.
1. original: [6 3 4 5 2 1]
2. Add index:[6 3 4 5 2 1]
                          1 2 3 4 5 6
3. Swap index和content:[1 2 3 4 5 6]
                                            6 3 4 5 2 1
4. 根據index做sort:[6 5 2 3 4 1]
                                    1 2 3 4 5 6

●S-boxes: m x n substitution unit
e.g.
y1 = x1 + x2 + x3
y2 = x1

●operation:
  ○XOR
  ○circular shift
  ○swap:circular shift n/2
  ○split and combine

●diffusion:將plaintext 和 ciphertext 的關係藏起

●confusion:將ciphertext和key的關係藏起

●product cipher:a complex cipher 結合substitution, permutation ... other components
  modern block cipher 都是product cipher
  可分為兩種:
  ○Feistel cipher
  ○non-Feistel cipher



5.2modern stream cipher:
●synchronous stream cipher:key和plaintext或ciphertext無關
  ○Feedback shift register(FSR):產生key
   e.g.
     b4  =  b1+ b0


→LFSR產生的key為pseudo random(有cycle,最大cycle為2m-1,m為cell數量)
→可以用polynomial 去表示
e.g.   b4 = b1 + b0
可用 x4 + x +1  表示

●non-synchronous stream cipher:每一個key stream 裡的key均depend on先前的plaintext或ciphertext



2014年12月16日 星期二

Cryptography and Network Security-Ch4

Mathematics of cryptography Part 2: Algebraic Structure

4.1 Algebraic Structure
●five property:
   ●closure (封閉性)
   ●associativity (結合性)
   ●commutativity (交換性)
   ●existence of identity:和任意element 做運算,結果=那個element。e.g.:加法下的0
   ●existence of inverse:自己和inverse做運算,結果= identity
 1. Groups: set of element + operation   (滿足property 1 2 4 5)
    e.g. G = <Zn, +>
   ●Abelian group:滿足交換性
   ●subgroup:subgroup裡的element均屬於group,operation 結果也相同
   ●cyclic subgroup:可以用element的power產生出來
 

※Lagrange' s theorem:H是G的subgroup,
order of H 是order of G的因數
 ●order of a group:產生cycle的最高項
  e.g. G = <Z10*, x>
    ord(1) = 1
    ord(3) = 4
    ord(7) = 4
    ord(9) = 2
  group order:2


  2. Rings:R = <{}, ├, ┤>
     {}為set
     ├ 為operation 1 滿足property 1 2 4 5
     ┤ 為operation 2 滿足property 1 2


  3. Fields:F = <{}, ├, ┤>
     {}為set
     ├ 為operation 1 滿足property 1 2 4 5
     ┤ 為operation 2 滿足property 1 2 3 4 5
    (├的identity 在┤不可有inverse)
  ●Galois Field:GF(p ^n)
    p is prime



4.2 GF(2^n) fields
  ●可以用n-1 degree 的polynomial 表示
   f(x) = an-1 xn-1  + a n-2 xn-2+...+a0x0
   e.g. GF(22):f(x) = 1x + 0
                                    0      0
                                    0      1
                                    1      1
  ●addition = subtraction = bit-wise XOR
  ●multiplication:相乘結果需用modulus polynomial (irreducible polynomial)去reduce (除以irreducible polynomial取餘數)
  ●inverse of polynomial:
    利用Euclidean algorithm 或將所有table generate出來
    e.g. inverse of x5 modulo x8 + x4 + x3 + x + 1


  ●相乘algorithm:
    e.g. P1 = 000100110, P2 = 10011110, modulus = 100011010
    P2每次向左shift一次
    當上次結果最高位為1時再和modulus做XOR(較低8位)
,   最後將P1為1的那一個結果做XOR (圖中話底線的)
 
 

  ●利用generator 去定義elements of GF(2n)
{0, g0, g1, g2, ..., gN}, where N = 2n-2


2014年12月8日 星期一

Cryptography and Network Security-Ch3

Chapter3 traditional symmetric-key cipher

<3.1> Introduction
名詞解釋
ciphertext:密文
plaintext:明文

encryption(加密): C = Ek(P)
decryption(解密): P = Dk(C)



cryptography:create secret code的科學
cryptanalysis:break codes的科學
    1. ciphertext-only attack:只知道密文
    2. known-plaintext attack:有歷史密文明文對,但不能選擇
    3. chosen-plaintext attack:有密文,可以選擇明文
    4. chosen-ciphertext attack:有密文,可以選擇密文



※Kerckhoff's principle:
(假設adversary 知道encryption/ decryption algorithm)
防止cipher attack只能根據key的secrecy


<3.2>substitution cipher
 1. monoalphabetic cipher:明文中相同的符號只有一種對應
       (e.g. 所有b -> a)

      (1).additive cipher(shift cipher):C = P + K
              ※frequency analysis:計算密文中的字元或字串出現次數,猜測對應的明文

      (2)multiplication cipher:C = P * K
                                                P = C * K^(-1)

      (3)Affine cipher:先用key1做乘法,再用key2做加法
                                    C = P * k1 + k2

      (4)自己定義對應

 2. polyalphabetic cipher:明文中相同字母會有不同密文
     (1). auto key:key 為前一位的明文
                              Ci = Pi + Ki
                              Pi = Ci - Ki                      
                             ki = (k, P1, P2, P3, ...)


    (2) play fair:
L G D B A
Q M H E C
U R N I/J F
X V S O K
Z Y W T P

          同行:右移
          同列:下移
          不同行不同列:對角
           e.g he -> EC
                 lx -> QZ
                 lo -> BX

   (3)Vigenere cipher:Ci = Pi + k
        (m組 additive)      Pi = Ci - k
       k = [(k1, k2, ,kn), (k1, k2, ,kn), ...]
      e.g. PASCALPASCALPA...

  (4) Hill cipher:use matrix

C = P * K


P = C * K ^ (-1)
  (5) one time pad:key 為 random

  (6) rotor cipher:rotor轉一次有新的substitution

  (7) Enigma machine:


<3.3>transposition cipher:
1.  keyless transposition:
   (1) 類似rail fence:分兩行寫
明文:meet me at the...
          m    e    a    h...
              e    t    t     e
密文:
   meah....ette
   (2) write row by row, transfer column by coulmn

2. keyed transposition:將plaintext分為groups,用key去排列字元
    e.g.   3 1 2
             3表示原本的位子為3
所以 abc -> cab

※key inversion in transposition cipher:將index寫出來,根據原陣列做sorting,新的index陣列極為inversion
e.g
2 6 3 1 4 7 5 (key)
1 2 3 4 5 6 7 (index)
         ↓
1 2 3 4 5 6 7
4 1 3 5 7 2 6

inversion為4 1 3 5 7 2 6

※可以用matrix表達過程

※兩次transposition 和一次transposition效果一樣
<3.4>
※stream cipher:一個plaintext即可對應出一個ciphertext
※block cipher:需等一個block才可加密(e.g. play fair)



練習題:
1.     In each of the following ciphers, what is the maximum number of characters that will be changed in the ciphertext if only a single character is changed in the plaintext?

a.     Additive
b.     Multiplicative
c.      Affine
d.     Vigenere
e.     Auto-key
f.       One-time pad
g.      Rotor
h.     Enigma



2.  Use a brute-force attack to decipher the following message enciphered by Alice using an additive cipher. Suppose that Alice always uses a key that is close to her birthday, which is on the 13th of the month:
NCJAEZRCLASJLYODEPRLYZRCLASJLCPEHZDTOPDZQLNZTY 

3.     Use a one-letter frequency attack to decipher the following message. Assume that you know it is enciphered using monoalphabetic substitution cipher.

ONHOVEJHWOBEVGWOCBWHNUGBLHGBGR

4.     Assume that punctuation marks (periods, question marks, and spaces) are added to the encryption alphabet of a Hill cipher, then a 2*2 key matrix in Z29 can be used for encryption and decryption.

a.     Find the total number of possible matrices.


b.     It has been proved that the total number of invertible matrices is (N2 -1)(N2 - N), where N is the number of alphabet size. Find the key domain of a Hill cipher using this alphabet. 

5.     Use a Kasiski test and single-frequency attack to break the following ciphertext. You know that is has been created with Vigenere cipher
MPYIGOBSRMIDBSYRDIKATXAILFDFKXTPPSNTTJIGTHDELT
TXAIREIHSVOBSMLUCFIOEPZIWACRFXICUVXVTOPXDLWPENDHPTSI
DDBXWWTZPHNSOCLOUMSNRCCVUUXZHHNWSVXAUHIK

LXTIMOICHTYPBHMHXGXHOLWPEWWWWDALOCTSQZELT

NOTE:五行要分開計算





Ans
1.
 a. 1
 b. 1
 c. 1
 d. 1
 e. 2
 f. 1
 g. 1
 h. 1

2.
key = 11
ans : cryptography and steganography are two sides of a coin

3.
plaintext: One of the most famous men was Ceasar

4.
a.
294 = 707281
b.
 (292 -1)(292 - 29) = 62080

5.
key = a poet
MAKE NO MENTION OF ROUGH TIMES FORGET ABOUT EVENTS PAST
TIME YET TO COME IS UNREVEALED AND BEING REVEALED WILL NOT LAST
DONT DWELL ON DAYS OF YOUR NOR BUILD ON HERE AFTER
LIFE TO TODAY AND THIS TOO WILL WHISK AWAY AS BLAST


可以參考網站:

                  http://www.richkni.co.uk/php/crypta/freq.php
                  http://www.counton.org/explorer/codebreaking/frequency-analysis.php