gm_rs/
sm4.rs

1use std::error;
2use std::fmt::{Display, Formatter};
3
4static SBOX: [u8; 256] = [
5    0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05,
6    0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99,
7    0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62,
8    0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6,
9    0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8,
10    0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35,
11    0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87,
12    0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e,
13    0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1,
14    0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3,
15    0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f,
16    0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51,
17    0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8,
18    0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0,
19    0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84,
20    0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48,
21];
22
23static FK: [u32; 4] = [0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc];
24
25static CK: [u32; 32] = [
26    0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269, 0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9,
27    0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249, 0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9,
28    0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229, 0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299,
29    0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209, 0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279,
30];
31
32pub type Sm4Result<T> = Result<T, Sm4Error>;
33
34pub enum Sm4Error {
35    ErrorBlockSize,
36    ErrorDataLen,
37    InvalidLastU8,
38}
39
40impl ::std::fmt::Debug for Sm4Error {
41    fn fmt(&self, f: &mut Formatter<'_>) -> ::std::fmt::Result {
42        write!(f, "{}", self)
43    }
44}
45
46impl From<Sm4Error> for &str {
47    fn from(e: Sm4Error) -> Self {
48        match e {
49            Sm4Error::ErrorBlockSize => "the block size of SM4 must be 16",
50            Sm4Error::ErrorDataLen => "the data len of SM4 must be 16",
51            Sm4Error::InvalidLastU8 => {
52                "the last u8 of cbc_decrypt out in SM4 must be positive which isn't greater than 16"
53            }
54        }
55    }
56}
57
58impl error::Error for Sm4Error {}
59
60impl Display for Sm4Error {
61    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
62        write!(
63            f,
64            "{}",
65            match self {
66                Sm4Error::ErrorBlockSize => "the block size of SM4 must be 16",
67                Sm4Error::ErrorDataLen => "the data len of SM4 must be 16",
68                Sm4Error::InvalidLastU8 => {
69                    "the last u8 of cbc_decrypt out in SM4 must be positive which isn't greater than 16"
70                }
71            }
72        )
73    }
74}
75
76/// (b0 , b1 , b2 , b3 ) = τ( A) = ( Sbox ( a0 ), Sbox ( a1 ), Sbox ( a2 ), Sbox ( a3 ) )
77#[inline]
78fn tau(a: u32) -> u32 {
79    let mut buf = a.to_be_bytes();
80    buf[0] = SBOX[buf[0] as usize];
81    buf[1] = SBOX[buf[1] as usize];
82    buf[2] = SBOX[buf[2] as usize];
83    buf[3] = SBOX[buf[3] as usize];
84    u32::from_be_bytes(buf)
85}
86
87/// L: linear transformation
88/// C = L(B) = B ⊕ (B <<< 2) ⊕ (B <<< 10) ⊕ (B <<< 18) ⊕ (B <<< 24)
89#[inline]
90fn el(b: u32) -> u32 {
91    b ^ b.rotate_left(2) ^ b.rotate_left(10) ^ b.rotate_left(18) ^ b.rotate_left(24)
92}
93
94#[inline]
95fn el_prime(b: u32) -> u32 {
96    b ^ b.rotate_left(13) ^ b.rotate_left(23)
97}
98
99#[inline]
100fn t(val: u32) -> u32 {
101    el(tau(val))
102}
103
104#[inline]
105fn t_prime(val: u32) -> u32 {
106    el_prime(tau(val))
107}
108
109
110/// SM4 block cipher.
111/// # Example
112/// ```rust
113/// fn main() {
114///   use hex_literal::hex;
115///   use gm_rs::sm4::Sm4Cipher;
116///   let key = hex!("0123456789abcdeffedcba9876543210");
117///   let plaintext = key.clone();
118///   let ciphertext = hex!("681edf34d206965e86b3e94f536e4246");
119///   let cipher = Sm4Cipher::new(&key).unwrap();
120///   let enc = cipher.encrypt(&plaintext).unwrap();
121///   assert_eq!(&ciphertext, enc.as_slice());
122/// }
123/// ```
124#[derive(Debug, Clone, Eq, PartialEq)]
125pub struct Sm4Cipher {
126    rk: [u32; 32],
127}
128
129impl Sm4Cipher {
130    pub fn new(k: &[u8]) -> Sm4Result<Sm4Cipher> {
131        let mut rk = [0u32; 32];
132        let mk = [
133            u32::from_be_bytes(k[0..4].try_into().unwrap()),
134            u32::from_be_bytes(k[4..8].try_into().unwrap()),
135            u32::from_be_bytes(k[8..12].try_into().unwrap()),
136            u32::from_be_bytes(k[12..16].try_into().unwrap()),
137        ];
138        let mut k = [mk[0] ^ FK[0], mk[1] ^ FK[1], mk[2] ^ FK[2], mk[3] ^ FK[3]];
139
140        for i in 0..8 {
141            k[0] ^= t_prime(k[1] ^ k[2] ^ k[3] ^ CK[i * 4]);
142            k[1] ^= t_prime(k[2] ^ k[3] ^ k[0] ^ CK[i * 4 + 1]);
143            k[2] ^= t_prime(k[3] ^ k[0] ^ k[1] ^ CK[i * 4 + 2]);
144            k[3] ^= t_prime(k[0] ^ k[1] ^ k[2] ^ CK[i * 4 + 3]);
145
146            rk[i * 4] = k[0];
147            rk[i * 4 + 1] = k[1];
148            rk[i * 4 + 2] = k[2];
149            rk[i * 4 + 3] = k[3];
150        }
151        Ok(Sm4Cipher { rk })
152    }
153
154    pub fn encrypt(&self, block: &[u8]) -> Sm4Result<Vec<u8>> {
155        let mut x = [
156            u32::from_be_bytes(block[0..4].try_into().unwrap()),
157            u32::from_be_bytes(block[4..8].try_into().unwrap()),
158            u32::from_be_bytes(block[8..12].try_into().unwrap()),
159            u32::from_be_bytes(block[12..16].try_into().unwrap()),
160        ];
161
162        let rk = &self.rk;
163        for i in 0..8 {
164            x[0] ^= t(x[1] ^ x[2] ^ x[3] ^ rk[i * 4]);
165            x[1] ^= t(x[2] ^ x[3] ^ x[0] ^ rk[i * 4 + 1]);
166            x[2] ^= t(x[3] ^ x[0] ^ x[1] ^ rk[i * 4 + 2]);
167            x[3] ^= t(x[0] ^ x[1] ^ x[2] ^ rk[i * 4 + 3]);
168        }
169
170        let mut out: [u8; 16] = [0; 16];
171        out[0..4].copy_from_slice(&x[3].to_be_bytes());
172        out[4..8].copy_from_slice(&x[2].to_be_bytes());
173        out[8..12].copy_from_slice(&x[1].to_be_bytes());
174        out[12..16].copy_from_slice(&x[0].to_be_bytes());
175
176        Ok(out.to_vec())
177    }
178
179    pub fn decrypt(&self, block: &[u8]) -> Sm4Result<Vec<u8>> {
180        let mut x = [
181            u32::from_be_bytes(block[0..4].try_into().unwrap()),
182            u32::from_be_bytes(block[4..8].try_into().unwrap()),
183            u32::from_be_bytes(block[8..12].try_into().unwrap()),
184            u32::from_be_bytes(block[12..16].try_into().unwrap()),
185        ];
186        let rk = &self.rk;
187        for i in 0..8 {
188            x[0] ^= t(x[1] ^ x[2] ^ x[3] ^ rk[31 - i * 4]);
189            x[1] ^= t(x[2] ^ x[3] ^ x[0] ^ rk[31 - (i * 4 + 1)]);
190            x[2] ^= t(x[3] ^ x[0] ^ x[1] ^ rk[31 - (i * 4 + 2)]);
191            x[3] ^= t(x[0] ^ x[1] ^ x[2] ^ rk[31 - (i * 4 + 3)]);
192        }
193        let mut out: [u8; 16] = [0; 16];
194        out[0..4].copy_from_slice(&x[3].to_be_bytes());
195        out[4..8].copy_from_slice(&x[2].to_be_bytes());
196        out[8..12].copy_from_slice(&x[1].to_be_bytes());
197        out[12..16].copy_from_slice(&x[0].to_be_bytes());
198        Ok(out.to_vec())
199    }
200}
201
202pub enum CipherMode {
203    Cfb,
204    Ofb,
205    Ctr,
206    Cbc,
207}
208
209pub struct Sm4CipherMode {
210    cipher: Sm4Cipher,
211    mode: CipherMode,
212}
213
214fn block_xor(a: &[u8], b: &[u8]) -> [u8; 16] {
215    let mut out: [u8; 16] = [0; 16];
216    for i in 0..16 {
217        out[i] = a[i] ^ b[i];
218    }
219    out
220}
221
222fn block_add_one(a: &mut [u8]) {
223    let mut carry = 1;
224    for i in 0..16 {
225        let (t, c) = a[15 - i].overflowing_add(carry);
226        a[15 - i] = t;
227        if !c {
228            return;
229        }
230        carry = c as u8;
231    }
232}
233
234impl Sm4CipherMode {
235    pub fn new(key: &[u8], mode: CipherMode) -> Sm4Result<Sm4CipherMode> {
236        let cipher = Sm4Cipher::new(key)?;
237        Ok(Sm4CipherMode { cipher, mode })
238    }
239
240    pub fn encrypt(&self, data: &[u8], iv: &[u8]) -> Sm4Result<Vec<u8>> {
241        if iv.len() != 16 {
242            return Err(Sm4Error::ErrorBlockSize);
243        }
244        match self.mode {
245            CipherMode::Cfb => self.cfb_encrypt(data, iv),
246            CipherMode::Ofb => self.ofb_encrypt(data, iv),
247            CipherMode::Ctr => self.ctr_encrypt(data, iv),
248            CipherMode::Cbc => self.cbc_encrypt(data, iv),
249        }
250    }
251
252    pub fn decrypt(&self, data: &[u8], iv: &[u8]) -> Sm4Result<Vec<u8>> {
253        if iv.len() != 16 {
254            return Err(Sm4Error::ErrorBlockSize);
255        }
256        match self.mode {
257            CipherMode::Cfb => self.cfb_decrypt(data, iv),
258            CipherMode::Ofb => self.ofb_encrypt(data, iv),
259            CipherMode::Ctr => self.ctr_encrypt(data, iv),
260            CipherMode::Cbc => self.cbc_decrypt(data, iv),
261        }
262    }
263
264    fn cfb_encrypt(&self, data: &[u8], iv: &[u8]) -> Result<Vec<u8>, Sm4Error> {
265        let block_num = data.len() / 16;
266        let tail_len = data.len() - block_num * 16;
267
268        let mut out: Vec<u8> = Vec::new();
269        let mut vec_buf: Vec<u8> = vec![0; 16];
270        vec_buf.clone_from_slice(iv);
271
272        // Normal
273        for i in 0..block_num {
274            let enc = self.cipher.encrypt(&vec_buf[..])?;
275            let ct = block_xor(&enc, &data[i * 16..i * 16 + 16]);
276            for i in ct.iter() {
277                out.push(*i);
278            }
279            vec_buf.clone_from_slice(&ct);
280        }
281
282        // Last block
283        let enc = self.cipher.encrypt(&vec_buf[..])?;
284        for i in 0..tail_len {
285            let b = data[block_num * 16 + i] ^ enc[i];
286            out.push(b);
287        }
288        Ok(out)
289    }
290
291    fn cfb_decrypt(&self, data: &[u8], iv: &[u8]) -> Result<Vec<u8>, Sm4Error> {
292        let block_num = data.len() / 16;
293        let tail_len = data.len() - block_num * 16;
294
295        let mut out: Vec<u8> = Vec::new();
296        let mut vec_buf: Vec<u8> = vec![0; 16];
297        vec_buf.clone_from_slice(iv);
298
299        // Normal
300        for i in 0..block_num {
301            let enc = self.cipher.encrypt(&vec_buf[..])?;
302            let ct = &data[i * 16..i * 16 + 16];
303            let pt = block_xor(&enc, ct);
304            for i in pt.iter() {
305                out.push(*i);
306            }
307            vec_buf.clone_from_slice(ct);
308        }
309
310        // Last block
311        let enc = self.cipher.encrypt(&vec_buf[..])?;
312        for i in 0..tail_len {
313            let b = data[block_num * 16 + i] ^ enc[i];
314            out.push(b);
315        }
316        Ok(out)
317    }
318
319    fn ofb_encrypt(&self, data: &[u8], iv: &[u8]) -> Result<Vec<u8>, Sm4Error> {
320        let block_num = data.len() / 16;
321        let tail_len = data.len() - block_num * 16;
322
323        let mut out: Vec<u8> = Vec::new();
324        let mut vec_buf: Vec<u8> = vec![0; 16];
325        vec_buf.clone_from_slice(iv);
326
327        // Normal
328        for i in 0..block_num {
329            let enc = self.cipher.encrypt(&vec_buf[..])?;
330            let ct = block_xor(&enc, &data[i * 16..i * 16 + 16]);
331            for i in ct.iter() {
332                out.push(*i);
333            }
334            vec_buf.clone_from_slice(&enc);
335        }
336
337        // Last block
338        let enc = self.cipher.encrypt(&vec_buf[..])?;
339        for i in 0..tail_len {
340            let b = data[block_num * 16 + i] ^ enc[i];
341            out.push(b);
342        }
343        Ok(out)
344    }
345
346    fn ctr_encrypt(&self, data: &[u8], iv: &[u8]) -> Result<Vec<u8>, Sm4Error> {
347        let block_num = data.len() / 16;
348        let tail_len = data.len() - block_num * 16;
349
350        let mut out: Vec<u8> = Vec::new();
351        let mut vec_buf: Vec<u8> = vec![0; 16];
352        vec_buf.clone_from_slice(iv);
353
354        // Normal
355        for i in 0..block_num {
356            let enc = self.cipher.encrypt(&vec_buf[..])?;
357            let ct = block_xor(&enc, &data[i * 16..i * 16 + 16]);
358            for i in ct.iter() {
359                out.push(*i);
360            }
361            block_add_one(&mut vec_buf[..]);
362        }
363
364        // Last block
365        let enc = self.cipher.encrypt(&vec_buf[..])?;
366        for i in 0..tail_len {
367            let b = data[block_num * 16 + i] ^ enc[i];
368            out.push(b);
369        }
370        Ok(out)
371    }
372
373    fn cbc_encrypt(&self, data: &[u8], iv: &[u8]) -> Result<Vec<u8>, Sm4Error> {
374        let block_num = data.len() / 16;
375        let remind = data.len() % 16;
376
377        let mut out: Vec<u8> = Vec::new();
378        let mut vec_buf: Vec<u8> = vec![0; 16];
379        vec_buf.copy_from_slice(iv);
380
381        // Normal
382        for i in 0..block_num {
383            let ct = block_xor(&vec_buf, &data[i * 16..i * 16 + 16]);
384            let enc = self.cipher.encrypt(&ct)?;
385
386            out.extend_from_slice(&enc);
387            vec_buf = enc;
388        }
389
390        if remind != 0 {
391            let mut last_block = [16 - remind as u8; 16];
392            last_block[..remind].copy_from_slice(&data[block_num * 16..]);
393
394            let ct = block_xor(&vec_buf, &last_block);
395            let enc = self.cipher.encrypt(&ct)?;
396            out.extend_from_slice(&enc);
397        } else {
398            let ff_padding = block_xor(&vec_buf, &[0x10; 16]);
399            let enc = self.cipher.encrypt(&ff_padding)?;
400            out.extend_from_slice(&enc);
401        }
402
403        Ok(out)
404    }
405
406    fn cbc_decrypt(&self, data: &[u8], iv: &[u8]) -> Result<Vec<u8>, Sm4Error> {
407        let data_len = data.len();
408        let block_num = data_len / 16;
409        if data_len % 16 != 0 {
410            return Err(Sm4Error::ErrorDataLen);
411        }
412
413        let mut out: Vec<u8> = Vec::new();
414        let mut vec_buf = [0; 16];
415        vec_buf.copy_from_slice(iv);
416
417        // Normal
418        for i in 0..block_num {
419            let enc = self.cipher.decrypt(&data[i * 16..i * 16 + 16])?;
420            let ct = block_xor(&vec_buf, &enc);
421
422            for j in ct.iter() {
423                out.push(*j);
424            }
425            vec_buf.copy_from_slice(&data[i * 16..i * 16 + 16]);
426        }
427
428        let last_u8 = out[data_len - 1];
429        if last_u8 > 0x10 || last_u8 == 0 {
430            return Err(Sm4Error::InvalidLastU8);
431        }
432        out.resize(data_len - last_u8 as usize, 0);
433
434        Ok(out)
435    }
436}
437
438#[cfg(test)]
439mod sm4test {
440    use crate::sm4::Sm4Cipher;
441    use hex_literal::hex;
442
443    #[test]
444    fn test_en_1() {
445        let key = hex!("0123456789abcdeffedcba9876543210");
446        let plaintext = key.clone();
447        let ciphertext = hex!("681edf34d206965e86b3e94f536e4246");
448
449        let cipher = Sm4Cipher::new(&key).unwrap();
450
451        let enc = cipher.encrypt(&plaintext).unwrap();
452        assert_eq!(&ciphertext, enc.as_slice());
453    }
454
455    #[test]
456    fn test_en_2() {
457        let key = hex!("0123456789abcdeffedcba9876543210");
458        let plaintext = key.clone();
459        let ciphertext = hex!("595298c7c6fd271f0402f804c33d3f66");
460
461        let cipher = Sm4Cipher::new(&key).unwrap();
462
463        let mut block = plaintext.to_vec();
464        for _ in 0..1_000_000 {
465             block = cipher.encrypt(&block.as_slice()).unwrap();
466        }
467        assert_eq!(&ciphertext, block.as_slice());
468    }
469}