silk.crypto.sm4.
Encrypt with the SM4 block cipher (GB/T 32907-2016, ISO/IEC 18033-3).
When to use#
Use Sm4 when a format names SM4, such as sm4-cbc or sm4-ctr in OpenSSL or Node.js. Run
it in a mode from silk.crypto.block_cipher, such as Cbc<Sm4>.
Details#
The key and the block are 16 bytes, and there are 32 rounds. Sm4 conforms to BlockCipher.
Nothing allocates.
Gotchas#
The S-box is a table lookup, so the time of a block can depend on the key and the data through the cache, as in OpenSSL's portable code. The value holds key material and is not erased when it is dropped.
Examples#
Encrypt one block#
import silk.crypto.block_cipher { BlockCipher, BlockCipherError }
import silk.crypto.sm4 { Sm4 }
import silk.core.result { Result }
pub fn main() -> i32 {
// The example of GB/T 32907-2016 appendix A.
let key: [u8; 16] = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10]
let cipher = match Sm4.make(&key) {
Result<Sm4, BlockCipherError>.Success { value } => move value
Result<Sm4, BlockCipherError>.Failure { error: _ } => {
return 1
}
}
let mut block = key
cipher.encryptBlock(&mut block)
if block[0] != 0x68 || block[1] != 0x1e || block[15] != 0x46 {
return 1
}
cipher.decryptBlock(&mut block)
if block[0] != 0x01 || block[15] != 0x10 {
return 1
}
return 0
}Import as Sm4 with import silk.crypto.sm4 { Sm4 }.
Public declarations: 1.
Sm4#
pub struct Sm4An SM4 key schedule.
Details#
Make one with Sm4.make and run it in a mode from silk.crypto.block_cipher, or call
encryptBlock and decryptBlock of BlockCipher on one 16-byte block.
Implementation Sm4#
impl Sm4Associated function make#
pub fn make(key: &[u8]) -> Result<Sm4, BlockCipherError>Returns the key schedule of the 16-byte key.
Errors#
InvalidKeyLengthifkeyis not 16 bytes.
Implementation BlockCipher for Sm4#
impl BlockCipher for Sm4Operation blockLength#
fn blockLength(self: &Self) -> usizeReturns 16.
Operation encryptBlock#
fn encryptBlock(self: &Self, block: &mut [u8; 16]) -> ()Encrypts the 16 bytes of block in place.
Operation decryptBlock#
fn decryptBlock(self: &Self, block: &mut [u8; 16]) -> ()Decrypts the 16 bytes of block in place.
Category: Cryptography.
Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, x86_64-pc-windows-msvc, wasm64-unknown-unknown.