Go 国密 sm2 sm3 sm4

本文仅供个人学习研究,如果涉及侵权,敬请告知!

国密

SM1 为对称加密。其加密强度与AES相当。该算法不公开,调用该算法时,需要通过加密芯片的接口进行调用。

SM2 为非对称加密,基于ECC。该算法已公开。由于该算法基于ECC,故其签名速度与秘钥生成速度都快于RSA。ECC 256位(SM2采用的就是ECC 256位的一种)安全强度比RSA 2048位高,但运算速度快于RSA。

SM3 消息摘要。可以用MD5作为对比理解。该算法已公开。校验结果为256位。

SM4 无线局域网标准的分组数据算法。对称加密,密钥长度和分组长度均为128位。

国产密码算法(国密算法)是指国家密码局认定的国产商用密码算法,在金融领域目前主要使用公开的SM2、SM3、SM4三类算法,分别是非对称算法、哈希算法和对称算法。

SM2

SM2算法:SM2椭圆曲线公钥密码算法是我国自主设计的公钥密码算法,包括SM2-1椭圆曲线数字签名算法,SM2-2椭圆曲线密钥交换协议,SM2-3椭圆曲线公钥加密算法,分别用于实现数字签名密钥协商和数据加密等功能。SM2算法与RSA算法不同的是,SM2算法是基于椭圆曲线上点群离散对数难题,相对于RSA算法,256位的SM2密码强度已经比2048位的RSA密码强度要高。

SM3

SM3算法:SM3杂凑算法是我国自主设计的密码杂凑算法,适用于商用密码应用中的数字签名和验证消息认证码的生成与验证以及随机数的生成,可满足多种密码应用的安全需求。为了保证杂凑算法的安全性,其产生的杂凑值的长度不应太短,例如MD5输出128比特杂凑值,输出长度太短,影响其安全性SHA-1算法的输出长度为160比特,SM3算法的输出长度为256比特,因此SM3算法的安全性要高于MD5算法和SHA-1算法。

SM4

SM4算法:SM4分组密码算法是我国自主设计的分组对称密码算法,用于实现数据的加密/解密运算,以保证数据和信息的机密性。要保证一个对称密码算法的安全性的基本条件是其具备足够的密钥长度,SM4算法与AES算法具有相同的密钥长度分组长度128比特,因此在安全性上高于3DES算法。

Go 语言实现国密

Go 语言实现国密,依赖第三方库,这里介绍一个基于Go语言的国密SM2/SM3/SM4加密算法库,GitHub 地址:
https://github.com/tjfoc/gmsm

安装:

go get -u github.com/tjfoc/gmsm
SM2

方法列表:

  • GenerateKey

生成随机秘钥。

func GenerateKey() (*PrivateKey, error) 
  • Sign

用私钥签名数据,成功返回以两个大数表示的签名结果,否则返回错误。

func Sign(priv *PrivateKey, hash []byte) (r, s *big.Int, err error)
  • Verify

用公钥验证数据签名, 验证成功返回True,否则返回False。

func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool 
  • Encrypt

用公钥加密数据,成功返回密文错误,否则返回错误。

func Encrypt(pub *PublicKey, data []byte) ([]byte, error) 
  • Decrypt

用私钥解密数据,成功返回原始明文数据,否则返回错误。

func Decrypt(priv *PrivateKey, data []byte) ([]byte, error)

实例:


func main() {
	priv, err := sm2.GenerateKey() // 生成密钥对
	if err != nil {
		log.Fatal(err)
	}
	msg := []byte("Tongji Fintech Research Institute")
	pub := &priv.PublicKey
	ciphertxt, err := pub.Encrypt(msg)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("加密结果:%x\n",ciphertxt)
	plaintxt,err :=  priv.Decrypt(ciphertxt)
	if err != nil {
		log.Fatal(err)
	}
	if !bytes.Equal(msg,plaintxt){
		log.Fatal("原文不匹配")
	}

	r,s,err := sm2.Sign(priv, msg)
	if err != nil {
		log.Fatal(err)
	}
	isok := sm2.Verify(pub,msg,r,s)
	fmt.Printf("Verified: %v\n", isok)
}
SM3

方法列表:

  • New

创建哈希计算实例

func New() hash.Hash 
  • Sum

返回SM3哈希算法摘要值

func Sum() []byte 

实例:

func main() {
	data := "test"
	h := sm3.New()
	h.Write([]byte(data))
	sum := h.Sum(nil)
	fmt.Printf("digest value is: %x\n",sum)
}
SM4

方法列表:

  • NewCipher

创建SM4密码分组算法模型,参数key长度只支持128比特。

func NewCipher(key []byte) (cipher.Block, error)

实例:

func main(){
        // 128比特密钥
        key := []byte("1234567890abcdef")
        // 128比特iv
        iv := make([]byte, sm4.BlockSize)
        data := []byte("Tongji Fintech Research Institute")
        ciphertxt,err := sm4Encrypt(key,iv, data)
        if err != nil{
            log.Fatal(err)
        }
        fmt.Printf("加密结果: %x\n", ciphertxt)
    }

    func sm4Encrypt(key, iv, plainText []byte) ([]byte, error) {
        block, err := sm4.NewCipher(key)
        if err != nil {
            return nil, err
        }
        blockSize := block.BlockSize()
        origData := pkcs5Padding(plainText, blockSize)
        blockMode := cipher.NewCBCEncrypter(block, iv)
        cryted := make([]byte, len(origData))
        blockMode.CryptBlocks(cryted, origData)
        return cryted, nil
    }

    func sm4Decrypt(key, iv, cipherText []byte) ([]byte, error) {
        block, err := sm4.NewCipher(key)
    	if err != nil {
        	return nil, err
    	}
    	blockMode := cipher.NewCBCDecrypter(block, iv)
    	origData := make([]byte, len(cipherText))
    	blockMode.CryptBlocks(origData, cipherText)
    	origData = pkcs5UnPadding(origData)
    	return origData, nil
    }
    // pkcs5填充
    func pkcs5Padding(src []byte, blockSize int) []byte {
        padding := blockSize - len(src)%blockSize
    	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    	return append(src, padtext...)
    }

    func pkcs5UnPadding(src []byte) []byte {
        length := len(src)
    	unpadding := int(src[length-1])
    	return src[:(length - unpadding)]
    }

总结

使用第三方库,可以解决 Go 语言的国密加密问题。

  • 0
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
Java 中实现国密算法 SM2SM3SM4 可以使用 Bouncy Castle 密码库。Bouncy Castle 是一个流行的密码库,支持多种密码算法,包括国密算法。 以下是一个简单的示例,说明如何在 Java 中使用 Bouncy Castle 实现 SM2SM3SM4: 1. 添加 Bouncy Castle 依赖 在 Maven 项目中,可以在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15to18</artifactId> <version>1.68</version> </dependency> ``` 2. SM2 加密和解密示例 ```java import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.generators.ECKeyPairGenerator; import org.bouncycastle.crypto.params.*; import org.bouncycastle.crypto.signers.SM2Signer; import org.bouncycastle.crypto.util.PrivateKeyFactory; import org.bouncycastle.crypto.util.PublicKeyFactory; import java.security.SecureRandom; public class SM2Example { public static void main(String[] args) throws Exception { // 生成密钥对 ECKeyPairGenerator ecKeyPairGenerator = new ECKeyPairGenerator(); SecureRandom secureRandom = new SecureRandom(); X9ECParameters ecParams = SECNamedCurves.getByName("sm2p256v1"); ECDomainParameters ecDomainParameters = new ECDomainParameters(ecParams.getCurve(), ecParams.getG(), ecParams.getN(), ecParams.getH(), ecParams.getSeed()); ECKeyGenerationParameters keyParams = new ECKeyGenerationParameters(ecDomainParameters, secureRandom); ecKeyPairGenerator.init(keyParams); AsymmetricCipherKeyPair keyPair = ecKeyPairGenerator.generateKeyPair(); // 加密 SM2Engine sm2Engine = new SM2Engine(); CipherParameters publicKeyParameters = PublicKeyFactory.createKey(keyPair.getPublic().getEncoded()); CipherParameters privateKeyParameters = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); sm2Engine.init(true, new ParametersWithRandom(publicKeyParameters, secureRandom)); byte[] plainText = "hello world".getBytes(); byte[] cipherText = sm2Engine.processBlock(plainText, 0, plainText.length); // 解密 sm2Engine.init(false, privateKeyParameters); byte[] decryptedText = sm2Engine.processBlock(cipherText, 0, cipherText.length); System.out.println(new String(decryptedText)); } } ``` 3. SM3 摘要示例 ```java import org.bouncycastle.crypto.digests.SM3Digest; public class SM3Example { public static void main(String[] args) { // 计算摘要 byte[] input = "hello world".getBytes(); SM3Digest digest = new SM3Digest(); digest.update(input, 0, input.length); byte[] result = new byte[digest.getDigestSize()]; digest.doFinal(result, 0); // 输出摘要 System.out.println(bytesToHex(result)); } private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray(); public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int i = 0; i < bytes.length; i++) { int v = bytes[i] & 0xFF; hexChars[i * 2] = HEX_ARRAY[v >>> 4]; hexChars[i * 2 + 1] = HEX_ARRAY[v & 0x0F]; } return new String(hexChars); } } ``` 4. SM4 加密和解密示例 ```java import org.bouncycastle.crypto.engines.SM4Engine; import org.bouncycastle.crypto.params.KeyParameter; import java.security.SecureRandom; public class SM4Example { public static void main(String[] args) { // 生成密钥 SecureRandom secureRandom = new SecureRandom(); byte[] key = new byte[16]; secureRandom.nextBytes(key); KeyParameter keyParameter = new KeyParameter(key); // 加密 SM4Engine sm4Engine = new SM4Engine(); sm4Engine.init(true, keyParameter); byte[] plainText = "hello world".getBytes(); byte[] cipherText = new byte[sm4Engine.getOutputSize(plainText.length)]; int length = sm4Engine.processBytes(plainText, 0, plainText.length, cipherText, 0); sm4Engine.doFinal(cipherText, length); // 解密 sm4Engine.init(false, keyParameter); byte[] decryptedText = new byte[sm4Engine.getOutputSize(cipherText.length)]; length = sm4Engine.processBytes(cipherText, 0, cipherText.length, decryptedText, 0); sm4Engine.doFinal(decryptedText, length); System.out.println(new String(decryptedText)); } } ``` 以上是实现 SM2SM3SM4 的简单示例,具体实现可以根据具体需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值