gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/sm4soft/padding/bloc_cryptor.go (about) 1 // Copyright (c) 2022 zhaochun 2 // core-gm is licensed under Mulan PSL v2. 3 // You can use this software according to the terms and conditions of the Mulan PSL v2. 4 // You may obtain a copy of Mulan PSL v2 at: 5 // http://license.coscl.org.cn/MulanPSL2 6 // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 7 // See the Mulan PSL v2 for more details. 8 9 /* 10 sm4soft 是sm4的纯软实现,基于tjfoc国密算法库`tjfoc/gmsm`做了少量修改。 11 对应版权声明: thrid_licenses/github.com/tjfoc/gmsm/版权声明 12 */ 13 14 package padding 15 16 import ( 17 "crypto/cipher" 18 "io" 19 ) 20 21 // P7BlockDecrypt 解密密文,并去除PKCS#7填充 22 // decrypter: 块解密器 23 // in: 密文输入流 24 // out: 明文输出流 25 func P7BlockDecrypt(decrypter cipher.BlockMode, in io.Reader, out io.Writer) error { 26 bufIn := make([]byte, 1024) 27 bufOut := make([]byte, 1024) 28 p7Out := NewPKCS7PaddingWriter(out, decrypter.BlockSize()) 29 for { 30 n, err := in.Read(bufIn) 31 if err != nil && err != io.EOF { 32 return err 33 } 34 if n == 0 { 35 break 36 } 37 decrypter.CryptBlocks(bufOut, bufIn[:n]) 38 _, err = p7Out.Write(bufOut[:n]) 39 if err != nil { 40 return err 41 } 42 } 43 return p7Out.Final() 44 } 45 46 // P7BlockEnc 以PKCS#7填充模式填充原文,并加密输出 47 // encrypter: 块加密器 48 // in: 明文输入流 49 // out: 密文输出流 50 func P7BlockEnc(encrypter cipher.BlockMode, in io.Reader, out io.Writer) error { 51 bufIn := make([]byte, 1024) 52 bufOut := make([]byte, 1024) 53 p7In := NewPKCS7PaddingReader(in, encrypter.BlockSize()) 54 for { 55 n, err := p7In.Read(bufIn) 56 if err != nil && err != io.EOF { 57 return err 58 } 59 if n == 0 { 60 break 61 } 62 encrypter.CryptBlocks(bufOut, bufIn[:n]) 63 _, err = out.Write(bufOut[:n]) 64 if err != nil { 65 return err 66 } 67 } 68 return nil 69 }