github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/sm4soft/padding/bloc_cryptor.go (about) 1 // Copyright 2022 s1ren@github.com/hxx258456. 2 3 /* 4 sm4soft 是sm4的纯软实现,基于tjfoc国密算法库`tjfoc/gmsm`做了少量修改。 5 对应版权声明: thrid_licenses/github.com/tjfoc/gmsm/版权声明 6 */ 7 8 package padding 9 10 import ( 11 "crypto/cipher" 12 "io" 13 ) 14 15 // P7BlockDecrypt 解密密文,并去除PKCS#7填充 16 // decrypter: 块解密器 17 // in: 密文输入流 18 // out: 明文输出流 19 func P7BlockDecrypt(decrypter cipher.BlockMode, in io.Reader, out io.Writer) error { 20 bufIn := make([]byte, 1024) 21 bufOut := make([]byte, 1024) 22 p7Out := NewPKCS7PaddingWriter(out, decrypter.BlockSize()) 23 for { 24 n, err := in.Read(bufIn) 25 if err != nil && err != io.EOF { 26 return err 27 } 28 if n == 0 { 29 break 30 } 31 decrypter.CryptBlocks(bufOut, bufIn[:n]) 32 _, err = p7Out.Write(bufOut[:n]) 33 if err != nil { 34 return err 35 } 36 } 37 return p7Out.Final() 38 } 39 40 // P7BlockEnc 以PKCS#7填充模式填充原文,并加密输出 41 // encrypter: 块加密器 42 // in: 明文输入流 43 // out: 密文输出流 44 func P7BlockEnc(encrypter cipher.BlockMode, in io.Reader, out io.Writer) error { 45 bufIn := make([]byte, 1024) 46 bufOut := make([]byte, 1024) 47 p7In := NewPKCS7PaddingReader(in, encrypter.BlockSize()) 48 for { 49 n, err := p7In.Read(bufIn) 50 if err != nil && err != io.EOF { 51 return err 52 } 53 if n == 0 { 54 break 55 } 56 encrypter.CryptBlocks(bufOut, bufIn[:n]) 57 _, err = out.Write(bufOut[:n]) 58 if err != nil { 59 return err 60 } 61 } 62 return nil 63 }