國密SM —— SM3單向雜湊、SM3案例實現、SM4分組密碼標準、Go語言實現SM4加密
阿新 • • 發佈:2018-11-25
func main() {
hash := sm3.New()
hash.Write([]byte("i am wek $$ The_Reader !"))
result := hash.Sum(nil)
println("sm3 hash = ",hex.EncodeToString(result))
hash2 := sm3.Sm3Sum([]byte("i am wek $$ The_Reader !"))
println("sm3 hash2 = ",hex.EncodeToString(hash2))
}
結果為:
SM4分組密碼標準
它將明文分成多個等長的模組(block),使用確定的演算法和對稱金鑰對每組分別加密解密。分組加密是極其重要的加密協議組成,SM4的金鑰長度及分組長度均為128bit。
SM4加密解密案例:
func SM4Encrypt(src []byte, key []byte) []byte { block, e := sm4.NewCipher(key) if e != nil { fmt.Println("newCrypther faild !") } a := block.BlockSize() - len(src)%block.BlockSize() repeat := bytes.Repeat([]byte{byte(a)},a) newsrc := append(src, repeat...) dst := make([]byte, len(newsrc)) blockMode := cipher.NewCBCEncrypter(block, key[:block.BlockSize()]) blockMode.CryptBlocks(dst,newsrc) return dst } func SM4Decrypto(dst,key []byte)[]byte{ block, e := sm4.NewCipher(key) if e!=nil{ fmt.Println("newcipher faild! ") } blockMode := cipher.NewCBCDecrypter(block, key[:block.BlockSize()]) src := make([]byte, len(dst)) blockMode.CryptBlocks(src,dst) num := int(src[len(src)-1]) newsrc := src[:len(src)-num] return newsrc } func main() { a := []byte("erl1233312") key := []byte("aabbccddaabbccdd") decrypto := SM4Encrypt(a,key) fmt.Println("sm4加密後:",hex.EncodeToString(decrypto)) i := SM4Decrypto(decrypto, key) fmt.Println("sm4解密後:",string(i)) }
結果為: