Domestic encryption algorithm - java implementation of SM3
1, Introduction of domestic encryption algorithm
The state commercial cipher management office has formulated a series of cipher standards, including SM1 (SCB2), SM2, SM3, SM4, SM7, SM9, Zuchongzhi cipher algorithm (ZUC), etc.
SM1, SM4, SM7 and ZUC are symmetric algorithms; SM2 and SM9 are asymmetric algorithms; SM3 is a hash algorithm. At present, these algorithms have been widely used in various fields. We look forward to the emergence of blockchain applications using state secret algorithms one day.
SM1 and SM7 algorithms are not public. When calling the algorithm, it needs to be called through the interface of the encryption chip; Few people understand these algorithms. Here we make a simple introduction to these national secret algorithms
1. SM1 symmetric password
SM1 algorithm is a block cipher algorithm, with a packet length of 128 bits and a key length of 128 bits. The security strength of the algorithm and the implementation performance of related software and hardware are equivalent to AES. The algorithm is not public and exists only in the chip in the form of IP core.
Using this algorithm, a series of chips, smart IC cards, smart password keys, encryption cards, encryption machines and other security products have been developed, which are widely used in various application fields of e-government, e-commerce and national economy (including important fields such as national government communication and police communication).
2. SM2 elliptic curve public key cryptography algorithm (vs ECDSA, ECDH)
SM2 algorithm is ECC elliptic curve cryptography mechanism, but it is different from ECDSA, ECDH and other international standards in signature and key exchange, but adopts a more secure mechanism. In addition, SM2 recommends a 256 bit curve as the standard curve.
SM2 standard includes four parts: general, digital signature algorithm, key exchange protocol and public key encryption algorithm. The implementation details and examples are described in detail in the appendix of each part.
SM2 algorithm mainly considers elliptic curves on prime fields Fp and F2m, and introduces the representation and operation of these two kinds of fields, as well as the representation, operation and multiple point calculation algorithms of elliptic curves on fields. Then it introduces the data conversion in the programming language, including the data conversion rules between integer and byte string, byte string and bit string, domain element and bit string, domain element and integer, point and byte string.
The parameter generation and verification of elliptic curve over finite field are described in detail. The parameters of elliptic curve include the selection of finite field, the parameters of elliptic curve equation, the selection of base points of elliptic curve group, etc., and the selection criteria are given for verification. Finally, the generation of key pair and the verification of public key on elliptic curve are given. The user's key pair is (s, sP), where s is the user's private key and sP is the user's public key. Due to the discrete logarithm problem, it is difficult to obtain s from sP. the generation details and verification methods of key pair are given for prime field and binary extended field. The knowledge in the general rules also applies to SM9 algorithm.
Based on the general principles, the digital signature algorithm (including digital signature generation algorithm and verification algorithm), key exchange protocol and public key encryption algorithm (including encryption algorithm and decryption algorithm) are given. The algorithm description, algorithm flow and related examples are given in each part.
Digital signature algorithm, key exchange protocol and public key encryption algorithm all use SM3 cryptographic hash algorithm and random number generator approved by the State Encryption administration. Digital signature algorithm, key exchange protocol and public key encryption algorithm select finite fields and elliptic curves according to the general rules, and generate key pairs.
SM2 algorithm is superior to RSA algorithm in many aspects (RSA develops early, is widely used, and SM2 takes the lead naturally). The security comparison with RSA is shown in the following figure
3. SM3 hash algorithm (vs SHA-256)
SM3 cryptographic hash (hash, hash) algorithm gives the calculation method and steps of hash function algorithm, and gives an operation example. This algorithm is suitable for digital signature and verification, message authentication code generation and verification and random number generation in commercial cryptographic applications, and can meet the security requirements of many cryptographic applications. Used in SM2 and SM9 standards.
This algorithm generates a hash value with a length of 256 bits for a 64th power bit message with an input length of less than 2 through filling and iterative compression. XOR, modulus, modulus addition, shift, and, or, non operation are used, which is composed of filling, iterative process, message expansion and compression functions. See SM3 standard for specific algorithms and operation examples.
In 2005, Wang et al. Gave the collision attack method of MD5 algorithm and SHA-1 algorithm. Now the widely used MD5 algorithm and SHA-1 algorithm are no longer secure algorithms.
SM3 cipher digest algorithm is the Chinese commercial cipher hash algorithm standard published by China National cipher administration in 2010. SM3 algorithm is suitable for digital signature and verification in commercial cryptographic applications. It is an improved algorithm based on SHA-256. SM3 algorithm adopts Merkle damgard structure. The message packet length is 512 bits and the summary value length is 256 bits.
The compression function of SM3 algorithm has a similar structure to that of SHA-256, but the design of SM3 algorithm is more complex. For example, each round of compression function uses two message words.
So far, the security of SM3 algorithm is relatively high.
SM3 is mainly used for digital signature And verification Message authentication code Generation and verification, random number generation, etc., and their algorithms are disclosed. According to the State Password Administration, its security and efficiency are equivalent to SHA-256.
4. SM4 symmetry algorithm (vs DES)
This algorithm is a grouping algorithm for WLAN products. The packet length of the algorithm is 128 bits and the key length is 128 bits. Both encryption algorithm and key expansion algorithm adopt 32 rounds of nonlinear iterative structure. The decryption algorithm has the same structure as the encryption algorithm, but the use order of the round key is opposite. The decryption round key is the reverse order of the encryption round key.
The algorithm adopts a nonlinear iterative structure. Each iteration is given by a wheel function, in which the wheel function is composed of a nonlinear transformation and a linear transformation, and the nonlinear transformation is given by S-box. Where rki is the round key, and the synthetic permutation T forms the round function. The generation of round key is similar to the process in the figure above. It is generated by the encryption key as input. The linear transformation in round function is different, and there are also some differences in parameters. See SM4 standard for specific description and examples of SM4 algorithm.
The purpose of International DES algorithm and domestic SM4 algorithm is to encrypt and protect the data in static storage and transmission channel. The main characteristics are as follows:
5. SM7 symmetric password
SM7 algorithm is a block cipher algorithm. The packet length is 128 bits and the key length is 128 bits. SM7 is applicable to contactless IC cards. Applications include identity recognition applications (access control card, work permit, entry permit), ticketing applications (large-scale event tickets, exhibition tickets), payment and pass card applications (integral consumption card, Campus All-in-one Card, enterprise all-in-one card, etc.).
6. SM9 identification cipher algorithm
In order to reduce the complexity of key and certificate management in public key system, Adi Shamir, an Israeli scientist and one of the inventors of RSA algorithm, proposed the concept of identity based cryptography in 1984. The identification password takes the user's identification (such as e-mail address, mobile phone number, QQ number, etc.) as the public key and omits the process of exchanging digital certificates and public keys, making the security system easy to deploy and manage. It is very suitable for end-to-end offline secure communication, cloud data encryption, attribute based encryption and policy based encryption. In 2008, the identification cipher algorithm was officially awarded the commercial cipher algorithm model SM9 (commercial cipher No. 9 algorithm) by the state cipher administration, which laid a solid foundation for the application of identification cipher technology in China.
SM9 algorithm does not need to apply for digital certificate and is suitable for the security of various emerging applications of Internet applications. Such as password service based on cloud technology, e-mail security, intelligent terminal protection, Internet of things security, cloud storage security and so on. These security applications can use the mobile phone number or e-mail address as the public key to realize data encryption, identity authentication, call encryption, channel encryption and other security applications. They are easy to use and easy to deploy, thus opening the door to popularize cryptographic algorithms.
7. ZUC algorithm
Zu Chongzhi's sequence cipher algorithm is a stream cipher algorithm independently studied in China. It is an international standard cipher algorithm used in mobile communication 4G network. The algorithm includes Zu Chongzhi algorithm (ZUC), encryption algorithm (128-EEA3) and integrity algorithm (128-EIA3). At present, ZUC algorithm has been optimized, including hardware implementation and Optimization for 128-EEA3 and 128-EIA3.
As a national strategic resource, cryptographic algorithm is more critical than ever in history. In the era of big data and cloud computing, key information is often obtained from massive data through data mining technology, so everyone's information protection is very important.
8. Password hash function
Cryptographic hash function (English: cryptographic hash function), also translated as cryptographic hash function, cryptographic hash function and cryptographic hash function, is Hash function A kind of. It is considered a Unidirectional function In other words, it is extremely difficult to push back the input data from the result output by the hash function. Such a one-way function is called "the pack horse of modern cryptography". The input data of this hash function is usually called message, and its output result is often called message digest or digest.
stay information safety In, there are many important applications that use cryptographic hash functions, such as digital signature ,Message authentication code.
II SM3
2.1 java implementation
SM3 digest algorithm corresponds to the popular hash algorithm MD5. The result is 32-bit bytes and can be converted into 64 bit hexadecimal characters
Refer to online post summary
import cn.hutool.crypto.SmUtil; import org.bouncycastle.crypto.digests.SM3Digest; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.pqc.math.linearalgebra.ByteUtils; import java.io.UnsupportedEncodingException; import java.security.Security; import java.util.Arrays; /** * @author chuchunqing * @date 2022/1/6 */ public class Sm3Utils { private static final String ENCODING = "UTF-8"; static { Security.addProvider(new BouncyCastleProvider()); } /** * sm3 Algorithmic encryption * @explain * @param paramStr * String to be encrypted * @return Returns a hexadecimal string of fixed length = 32 after encryption */ public static String encrypt(String paramStr){ // Converts the returned hash value to a hexadecimal string String resultHexString = ""; try { // Convert string to byte array byte[] srcData = paramStr.getBytes(ENCODING); // Call hash() byte[] resultHash = hash(srcData); // Converts the returned hash value to a hexadecimal string resultHexString = ByteUtils.toHexString(resultHash); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return resultHexString; } /** * Returns a byte array with length = 32 * @explain Generate corresponding hash value * @param srcData * @return */ public static byte[] hash(byte[] srcData) { SM3Digest digest = new SM3Digest(); //update the message digest with a single byte. digest.update(srcData, 0, srcData.length); byte[] hash = new byte[digest.getDigestSize()]; //close the digest, producing the final digest value. digest.doFinal(hash, 0); return hash; } /** * sm3 Algorithmic encryption * @explain * @param paramStr * String to be encrypted * @param key * secret key * @return Returns a hexadecimal string of fixed length = 32 after encryption */ public static String encryptPlus(String paramStr,String key){ // Converts the returned hash value to a hexadecimal string String resultHexString = ""; try { // Convert string to byte array byte[] srcData = paramStr.getBytes(ENCODING); // Call hash() byte[] resultHash = hmac(srcData,key.getBytes(ENCODING)); // Converts the returned hash value to a hexadecimal string resultHexString = ByteUtils.toHexString(resultHash); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return resultHexString; } /** * Encryption by key * @explain Specify the key to encrypt * @param key * secret key * @param srcData * Encrypted byte array * @return */ public static byte[] hmac(byte[] key, byte[] srcData) { KeyParameter keyParameter = new KeyParameter(key); SM3Digest digest = new SM3Digest(); HMac mac = new HMac(digest); mac.init(keyParameter); mac.update(srcData, 0, srcData.length); byte[] result = new byte[mac.getMacSize()]; mac.doFinal(result, 0); return result; } /** * Judge whether the source data is consistent with the encrypted data * @explain Verify whether the original array and the generated hash array are the same array and whether they are the same data * @param srcStr * Original string * @param sm3HexString * 16 Hexadecimal Strings * @return Verification results */ public static boolean verify(String srcStr, String sm3HexString) { boolean flag = false; try { //Encodes the string into a byte sequence using the specified character set, and stores the result in a new byte array byte[] srcData = srcStr.getBytes(ENCODING); //Hexadecimal -- > byte [] byte[] sm3Hash = ByteUtils.fromHexString(sm3HexString); byte[] newHash = hash(srcData); //Determine whether the arrays are equal if (Arrays.equals(newHash, sm3Hash)) { flag = true; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return flag; } /***********************Using Hutool tool class*****************************************************************************************/ /** * sm3 Algorithmic encryption * * @param paramStr String to be encrypted * @return Returns a hexadecimal string of fixed length = 32 after encryption * @explain */ public static String encryptSm3ByHutool(String paramStr) { return SmUtil.sm3(paramStr); } /** * Judge whether the source data is consistent with the encrypted data (Hutool) * * @param srcStr Original string * @param sm3HexString 16 Hexadecimal Strings * @return Verification results */ public static boolean verifySm3ByHutool(String srcStr, String sm3HexString) { boolean flag = false; if (sm3HexString.equals(encryptSm3ByHutool(srcStr))) { flag = true; } return flag; } /***********************Using Hutool tool class*****************************************************************************************/ }
3, Reference documents
Official documents:
- Password Industry Standardization Technical Committee;
- State Password Administration
- API for SM3Digest class;
Feel like a good blog post:
- [everyone knows cryptography] one of the easiest introductory tutorials of Java cryptography
- Station B - Shang Silicon Valley - cryptography of network security
- https://zhuanlan.zhihu.com/p/...
- https://blog.csdn.net/cg12905...
- https://jueee.github.io/2021/...
- https://www.jianshu.com/p/8c3...;
The picture comes from the Internet. If there is infringement, please contact me to delete it