forked from GmSSL/GmSSL-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSm4EcbExample.java
More file actions
74 lines (58 loc) · 1.88 KB
/
Sm4EcbExample.java
File metadata and controls
74 lines (58 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
* Copyright 2014-2023 The GmSSL Project. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
import org.gmssl.Sm4;
import org.gmssl.Random;
import java.util.Arrays;
public class Sm4EcbExample {
public static void main(String[] args) {
Random rng = new Random();
byte[] key = rng.randBytes(Sm4.KEY_SIZE);
int nblocks = 4;
byte[] plaintext = rng.randBytes(Sm4.BLOCK_SIZE * nblocks);
byte[] ciphertext = new byte[Sm4.BLOCK_SIZE * nblocks];
byte[] decrypted = new byte[Sm4.BLOCK_SIZE * nblocks];
int plaintextOffset, ciphertextOffset, decryptedOffset;
int i;
System.out.println("SM4-ECB Example");
System.out.print("Plaintext : ");
for (i = 0; i < plaintext.length; i++) {
System.out.printf("%02x", plaintext[i]);
}
System.out.print("\n");
// Encrypt
Sm4 sm4enc = new Sm4(key, true);
plaintextOffset = 0;
ciphertextOffset = 0;
for (i = 0; i < nblocks; i++) {
sm4enc.encrypt(plaintext, plaintextOffset, ciphertext, ciphertextOffset);
plaintextOffset += Sm4.BLOCK_SIZE;
ciphertextOffset += Sm4.BLOCK_SIZE;
}
System.out.print("Ciphertext : ");
for (i = 0; i < ciphertext.length; i++) {
System.out.printf("%02x", ciphertext[i]);
}
System.out.print("\n");
// Decrypt
Sm4 sm4dec = new Sm4(key, false);
ciphertextOffset = 0;
decryptedOffset = 0;
for (i = 0; i < nblocks; i++) {
sm4dec.encrypt(ciphertext, ciphertextOffset, decrypted, decryptedOffset);
ciphertextOffset += Sm4.BLOCK_SIZE;
decryptedOffset += Sm4.BLOCK_SIZE;
}
System.out.print("Decrypted : ");
for (i = 0; i < decrypted.length; i++) {
System.out.printf("%02x", decrypted[i]);
}
System.out.print("\n");
System.out.println("Decryption success : " + Arrays.equals(plaintext, decrypted));
}
}