sm4

package
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 12, 2026 License: Apache-2.0 Imports: 5 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sm4 实现国密 SM4 分组密码算法(GB/T 32907-2016)。

分组长度与密钥长度均为 128 位。Cipher 实现 crypto/cipher.Block 接口, 可直接配合标准库的 CBC、CTR、GCM 等分组模式使用;本包另外提供 ECB、CBC 两种带 PKCS#7 填充的便捷函数。

Index

Constants

View Source
const BlockSize = 16

BlockSize SM4 分组字节长度。

View Source
const KeySize = 16

KeySize SM4 密钥字节长度。

Variables

This section is empty.

Functions

func CBCDecrypt

func CBCDecrypt(secretData, key, iv []byte) ([]byte, error)

CBCDecrypt SM4-CBC 解密数据并去除 PKCS#7 填充。 key 与 iv 均需为 16 字节。

func CBCEncrypt

func CBCEncrypt(originData, key, iv []byte) ([]byte, error)

CBCEncrypt SM4-CBC 加密数据,明文按 PKCS#7 填充。 key 与 iv 均需为 16 字节。

func ECBDecrypt

func ECBDecrypt(secretData, key []byte) ([]byte, error)

ECBDecrypt SM4-ECB 解密数据并去除 PKCS#7 填充,key 需为 16 字节。

func ECBEncrypt

func ECBEncrypt(originData, key []byte) ([]byte, error)

ECBEncrypt SM4-ECB 加密数据,明文按 PKCS#7 填充,key 需为 16 字节。

注意:ECB 模式相同明文分组会产生相同密文分组,不隐藏数据模式, 仅在对接方协议明确要求时使用(如招商银行聚合支付的敏感字段加密); 新设计请优先选择 CBC 或 GCM。

func NewCipher

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

NewCipher 创建 SM4 分组密码实例,key 必须为 16 字节。

func PKCS7Padding

func PKCS7Padding(originData []byte, blockSize int) []byte

PKCS7Padding 按 PKCS#7 对明文补齐到 blockSize 的整数倍。 明文长度已是整数倍时会补一个完整分组,以保证去填充可逆。

func PKCS7UnPadding

func PKCS7UnPadding(originData []byte, blockSize int) ([]byte, error)

PKCS7UnPadding 去除 PKCS#7 填充。 与 aes 包中的同名函数不同,此处对填充做严格校验,非法填充返回错误, 避免把损坏的密文当作有效明文返回。

Types

type Cipher

type Cipher struct {
	// contains filtered or unexported fields
}

Cipher 是一个已完成密钥扩展的 SM4 实例,实现 cipher.Block 接口。

func (*Cipher) BlockSize

func (c *Cipher) BlockSize() int

BlockSize 返回分组字节长度。

func (*Cipher) Decrypt

func (c *Cipher) Decrypt(dst, src []byte)

Decrypt 解密 src 中的一个分组并写入 dst。

func (*Cipher) Encrypt

func (c *Cipher) Encrypt(dst, src []byte)

Encrypt 加密 src 中的一个分组并写入 dst。

type KeySizeError

type KeySizeError int

KeySizeError 表示密钥长度不合法。

func (KeySizeError) Error

func (k KeySizeError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL