Golang crypto-cipher.NewCBCEncrypter类(方法)实例源码

下面列出了Golang crypto-cipher.NewCBCEncrypter 类(方法)源码代码实例,从而了解它的用法。

作者:postfi    项目:gokeepassli   
func (c *DBCredentials) buildMasterKey(db *Database) ([]byte, error) {
	masterKey, err := c.buildCompositeKey()
	if err != nil {
		return nil, err
	}

	block, err := aes.NewCipher(db.Headers.TransformSeed)
	if err != nil {
		return nil, err
	}

	// http://crypto.stackexchange.com/questions/21048/can-i-simulate-iterated-aes-ecb-with-other-block-cipher-modes
	for i := uint64(0); i < db.Headers.TransformRounds; i++ {
		result := make([]byte, 16)
		crypter := cipher.NewCBCEncrypter(block, result)
		crypter.CryptBlocks(masterKey[:16], masterKey[:16])
		crypter = cipher.NewCBCEncrypter(block, result)
		crypter.CryptBlocks(masterKey[16:], masterKey[16:])
	}

	tmp := sha256.Sum256(masterKey)
	masterKey = tmp[:]

	masterKey = append(db.Headers.MasterSeed, masterKey...)
	masterHash := sha256.Sum256(masterKey)
	masterKey = masterHash[:]

	return masterKey, nil
}

作者:JFHSebastia    项目:goker   
func (s *descbc) Sign(algo, usage int, data ...[]byte) ([]byte, error) {
	var h hash.Hash

	switch algo {
	case signGssDes:
		sz := 0
		for _, d := range data {
			sz += len(d)
		}
		sz = (sz + 7) &^ 7
		u := make([]byte, sz)
		v := u[:0]
		for _, d := range data {
			v = append(v, d...)
		}

		iv := [8]byte{}
		b, _ := des.NewCipher(s.key)
		c := cipher.NewCBCEncrypter(b, iv[:])
		c.CryptBlocks(u, u)
		return u[len(u)-8:], nil

	case signGssMd5Des:
		h = md5.New()
		for _, d := range data {
			h.Write(d)
		}
		return s.Sign(signGssDes, usage, h.Sum(nil))

	case signMd5Des:
		h = md5.New()
	case signMd4Des:
		h = md4.New()
	default:
		return unkeyedSign(algo, usage, data...)
	}

	var key [8]byte
	for i := 0; i < 8; i++ {
		key[i] = s.key[i] ^ 0xF0
	}

	chk := make([]byte, 24)
	io.ReadFull(rand.Reader, chk[:8])

	h.Write(chk[:8])
	for _, d := range data {
		h.Write(d)
	}
	h.Sum(chk[8:])

	iv := [8]byte{}
	b, _ := des.NewCipher(s.key)
	c := cipher.NewCBCEncrypter(b, iv[:])
	c.CryptBlocks(chk, chk)
	return chk, nil
}

作者:mohof    项目:CryptoWrappe   
// encryptAES enrypts plaintext input with passed key, IV and mode in AES block cipher;
// and returns ciphertext output
func encryptAES(input []byte, output []byte, key, iv []byte, mode Mode) error {
	block, err := aes.NewCipher(key)
	if err != nil {
		return errors.New("Couldn't create block cipher.")
	}

	// Prepend IV to ciphertext.
	// Generate IV randomly if it is not passed
	if iv == nil {
		if iv = generateIV(aes.BlockSize); iv == nil {
			return errors.New("Couldn't create random initialization vector (IV).")
		}
	}
	copy(output, iv)

	switch mode {
	case CBC:
		if len(input)%aes.BlockSize != 0 {
			input = addPadding(input, aes.BlockSize)
		}
		mode := cipher.NewCBCEncrypter(block, iv)
		mode.CryptBlocks(output[aes.BlockSize:], input)
	case CFB:
		mode := cipher.NewCFBEncrypter(block, iv)
		mode.XORKeyStream(output[aes.BlockSize:], input)
	case CTR:
		mode := cipher.NewCTR(block, iv)
		mode.XORKeyStream(output[aes.BlockSize:], input)
	case OFB:
		mode := cipher.NewOFB(block, iv)
		mode.XORKeyStream(output[aes.BlockSize:], input)
	}
	return nil
}

作者:Cergo    项目:ercaptch   
func (t *t_captchaserv) get(w http.ResponseWriter, r *http.Request) {

	defer func() {
		if e := recover(); e != nil {
			fmt.Println(fmt.Errorf("%v", e))
		}
	}()
	if r.Method != "GET" {
		return
	}

	r.ParseForm()
	jsonp := r.FormValue("callback")

	rjson := <-t.iochan
	crypt := make([]byte, 17)
	fmt.Println(rjson.id)

	t.rwmu_chang_state.RLock()
	encrypter := cipher.NewCBCEncrypter(t.bcipher, t.iv[0].val)
	encrypter.CryptBlocks(crypt[1:], []byte(rjson.id))
	crypt[0] = t.iv[0].id
	rjson.id = v_captcha.c.Nodeid + base64.URLEncoding.EncodeToString(crypt)
	t.rwmu_chang_state.RUnlock()

	request := "{\"id\": \"" + rjson.id + "\", \n \"img\": \"" + rjson.img + "\"}"
	if jsonp != "" {
		request = jsonp + "(" + request + ");"
	}

	w.Header().Set("Content-Type", "text/javascript")
	w.Header().Set("Cache-Control", "no-store, no-cache")
	fmt.Fprint(w, request)

}

作者:RajibTheKin    项目:gc   
func ExampleNewCBCEncrypter() {
	key := []byte("example key 1234")
	plaintext := []byte("exampleplaintext")

	// CBC mode works on blocks so plaintexts may need to be padded to the
	// next whole block. For an example of such padding, see
	// https://tools.ietf.org/html/rfc5246#section-6.2.3.2. Here we'll
	// assume that the plaintext is already of the correct length.
	if len(plaintext)%aes.BlockSize != 0 {
		panic("plaintext is not a multiple of the block size")
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}

	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		panic(err)
	}

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)

	// It's important to remember that ciphertexts must be authenticated
	// (i.e. by using crypto/hmac) as well as being encrypted in order to
	// be secure.

	fmt.Printf("%x\n", ciphertext)
}

作者:jsi    项目:wecha   
// ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]
func AESEncryptMsg(random, rawXMLMsg []byte, appId string, aesKey [32]byte) (ciphertext []byte) {
	const (
		BLOCK_SIZE = 32             // PKCS#7
		BLOCK_MASK = BLOCK_SIZE - 1 // BLOCK_SIZE 为 2^n 时, 可以用 mask 获取针对 BLOCK_SIZE 的余数
	)

	appIdOffset := 20 + len(rawXMLMsg)
	contentLen := appIdOffset + len(appId)
	amountToPad := BLOCK_SIZE - contentLen&BLOCK_MASK
	plaintextLen := contentLen + amountToPad

	plaintext := make([]byte, plaintextLen)

	// 拼接
	copy(plaintext[:16], random)
	encodeNetworkByteOrder(plaintext[16:20], uint32(len(rawXMLMsg)))
	copy(plaintext[20:], rawXMLMsg)
	copy(plaintext[appIdOffset:], appId)

	// PKCS#7 补位
	for i := contentLen; i < plaintextLen; i++ {
		plaintext[i] = byte(amountToPad)
	}

	// 加密
	block, err := aes.NewCipher(aesKey[:])
	if err != nil {
		panic(err)
	}
	mode := cipher.NewCBCEncrypter(block, aesKey[:16])
	mode.CryptBlocks(plaintext, plaintext)

	ciphertext = plaintext
	return
}

作者:trigrass    项目:wechat_componen   
// Encrypt 方法用于对明文进行加密
func (w messageCrypter) encrypt(text string) (string, error) {
	message := []byte(text)

	buf := new(bytes.Buffer)
	if err := binary.Write(buf, binary.BigEndian, int32(len(message))); err != nil {
		return "", err
	}

	msgLen := buf.Bytes()

	randBytes := make([]byte, 16)
	if _, err := io.ReadFull(rand.Reader, randBytes); err != nil {
		return "", err
	}

	messageBytes := bytes.Join([][]byte{randBytes, msgLen, message, []byte(w.appID)}, nil)

	encoded := fillEncode(messageBytes)

	c, err := aes.NewCipher(w.key)
	if err != nil {
		return "", err
	}

	cbc := cipher.NewCBCEncrypter(c, w.iv)
	cbc.CryptBlocks(encoded, encoded)

	return base64.StdEncoding.EncodeToString(encoded), nil
}

作者:kostyl    项目:gccp   
func TestCBC_AES(t *testing.T) {
	for _, tt := range cbcAESTests {
		test := tt.name

		c, err := aes.NewCipher(tt.key)
		if err != nil {
			t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err)
			continue
		}

		encrypter := cipher.NewCBCEncrypter(c, tt.iv)
		d := make([]byte, len(tt.in))
		encrypter.CryptBlocks(d, tt.in)
		if !bytes.Equal(tt.out, d) {
			t.Errorf("%s: CBCEncrypter\nhave %x\nwant %x", test, d, tt.out)
		}

		decrypter := cipher.NewCBCDecrypter(c, tt.iv)
		p := make([]byte, len(d))
		decrypter.CryptBlocks(p, d)
		if !bytes.Equal(tt.in, p) {
			t.Errorf("%s: CBCDecrypter\nhave %x\nwant %x", test, d, tt.in)
		}
	}
}

作者:Andal    项目:gobo   
func NewAesCBCCrypter(key []byte, iv []byte) (*AesCBCCrypter, error) {
	l := len(key)
	if l != 32 && l != 24 && l != 16 {
		return nil, errors.New("The key argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.")
	}

	block, _ := aes.NewCipher(key)
	blockSize := block.BlockSize()
	if len(iv) != blockSize {
		return nil, errors.New("The length of iv must be the same as the Block's block size " + strconv.Itoa(blockSize))
	}

	this := &AesCBCCrypter{
		blockSize: blockSize,

		encryptBlockMode: cipher.NewCBCEncrypter(block, iv),
		decryptBlockMode: cipher.NewCBCDecrypter(block, iv),

		padding: &PKCS5Padding{
			BlockSize: blockSize,
		},
	}

	return this, nil
}

作者:Lenni    项目:syncthin   
func EncryptFilename(filename []byte, key string) (out []byte, err error) {
	// Buffer needs to be multiples of aes.BlockSize
	var buf []byte
	if len(filename)%aes.BlockSize != 0 {
		buf = make([]byte, ((len(filename)/aes.BlockSize)+1)*aes.BlockSize)
		copy(buf, filename)
	} else {
		buf = filename
	}

	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		panic(err)
	}

	// sha256 the filename to use as IV
	hash := sha256.New()
	hash.Write(filename)
	salt := hash.Sum(nil)

	if len(salt) < aes.BlockSize {
		panic("Salt too short")
	}

	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	out = make([]byte, aes.BlockSize+len(buf))
	iv := out[:aes.BlockSize]
	copy(iv, salt[:aes.BlockSize])

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(out[aes.BlockSize:], buf)

	return out, nil
}

作者:majestrat    项目:go-i2   
// encrypt tunnel data in place
func (t *Tunnel) Encrypt(td *TunnelData) {
	data := *td
	t.ivKey.Encrypt(data[16:1024], data[16:1024])
	layerBlock := cipher.NewCBCEncrypter(t.layerKey, data[:16])
	layerBlock.CryptBlocks(data[16:1024], data[16:1024])
	t.ivKey.Encrypt(data[16:1024], data[16:1024])
}

作者:caiolim    项目:webki   
func EncryptShimTicket(in []byte) []byte {
	name := TestShimTicketKey[:16]
	macKey := TestShimTicketKey[16:32]
	encKey := TestShimTicketKey[32:48]

	h := hmac.New(sha256.New, macKey)

	block, err := aes.NewCipher(encKey)
	if err != nil {
		panic(err)
	}

	// Use the zero IV for rewritten tickets.
	iv := make([]byte, block.BlockSize())
	cbc := cipher.NewCBCEncrypter(block, iv)
	pad := block.BlockSize() - (len(in) % block.BlockSize())

	out := make([]byte, 0, len(name)+len(iv)+len(in)+pad+h.Size())
	out = append(out, name...)
	out = append(out, iv...)
	out = append(out, in...)
	for i := 0; i < pad; i++ {
		out = append(out, byte(pad))
	}

	ciphertext := out[len(name)+len(iv):]
	cbc.CryptBlocks(ciphertext, ciphertext)

	h.Write(out)
	return h.Sum(out)
}

作者:lestrra    项目:go-jw   
// Seal fulfills the crypto.AEAD interface
func (c AesCbcHmac) Seal(dst, nonce, plaintext, data []byte) []byte {
	ctlen := len(plaintext)
	ciphertext := make([]byte, ctlen+c.Overhead())[:ctlen]
	copy(ciphertext, plaintext)
	ciphertext = padbuf.PadBuffer(ciphertext).Pad(c.blockCipher.BlockSize())

	cbc := cipher.NewCBCEncrypter(c.blockCipher, nonce)
	cbc.CryptBlocks(ciphertext, ciphertext)

	authtag := c.ComputeAuthTag(data, nonce, ciphertext)

	retlen := len(dst) + len(ciphertext) + len(authtag)

	ret := ensureSize(dst, retlen)
	out := ret[len(dst):]
	n := copy(out, ciphertext)
	n += copy(out[n:], authtag)

	if debug.Enabled {
		debug.Printf("Seal: ciphertext = %x (%d)\n", ciphertext, len(ciphertext))
		debug.Printf("Seal: authtag    = %x (%d)\n", authtag, len(authtag))
		debug.Printf("Seal: ret        = %x (%d)\n", ret, len(ret))
	}
	return ret
}

作者:useide    项目:notar   
func (alg *AesCbcHmac) Encrypt(aad, plainText, cek []byte) (iv, cipherText, authTag []byte, err error) {

	cekSizeBits := len(cek) << 3
	if cekSizeBits != alg.keySizeBits {
		return nil, nil, nil, errors.New(fmt.Sprintf("AesCbcHmac.Encrypt(): expected key of size %v bits, but was given %v bits.", alg.keySizeBits, cekSizeBits))
	}

	hmacKey := cek[0 : len(cek)/2]
	aesKey := cek[len(cek)/2:]

	if iv, err = arrays.Random(16); err != nil {
		return nil, nil, nil, err
	}

	var block cipher.Block

	if block, err = aes.NewCipher(aesKey); err != nil {
		return nil, nil, nil, err
	}

	padded := padding.AddPkcs7(plainText, 16)

	cipherText = make([]byte, len(padded), cap(padded))
	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(cipherText, padded)

	authTag = alg.computeAuthTag(aad, iv, cipherText, hmacKey)

	return iv, cipherText, authTag, nil
}

作者:pombredann    项目:sn   
func (c *AESCodec) Encrypt(b []byte) (cipherdata []byte, err error) {
	// PKCS#7: padd with n, where n is the number of bytes remaining
	// to reach a multiple of the block size
	l := len(b)

	n := aes.BlockSize - l%aes.BlockSize
	cipherdata = make([]byte, aes.BlockSize+l+n)

	iv := cipherdata[:aes.BlockSize]
	data := cipherdata[aes.BlockSize:]

	copy(data, b)
	for i := 0; i < n; i++ {
		data[l+i] = byte(n)
	}

	block, err := aes.NewCipher(c.key)
	if err != nil {
		return
	}
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return nil, err
	}

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(cipherdata[aes.BlockSize:], data)

	return
}

作者:acasaju    项目:dkeycza   
func (ak *aesKey) Encrypt(data []byte) ([]byte, error) {
	data = pkcs5pad(data, aes.BlockSize)
	iv := make([]byte, aes.BlockSize)
	io.ReadFull(rand.Reader, iv)
	aesCipher, err := aes.NewCipher(ak.key)
	if err != nil {
		return nil, err
	}
	// aes only ever created with CBC as a mode
	crypter := cipher.NewCBCEncrypter(aesCipher, iv)
	cipherBytes := make([]byte, len(data))
	crypter.CryptBlocks(cipherBytes, data)
	h := makeHeader(ak)
	msg := make([]byte, 0, kzHeaderLength+aes.BlockSize+len(cipherBytes)+hmacSigLength)
	msg = append(msg, h...)
	msg = append(msg, iv...)
	msg = append(msg, cipherBytes...)
	// we sign the header, iv, and ciphertext
	sig, err := ak.hmac.Sign(msg)
	if err != nil {
		return nil, err
	}
	msg = append(msg, sig...)
	return msg, nil
}

作者:Zemant    项目:go-secretcryp   
func (c LocalCrypter) Encrypt(plaintext string, encryptParams EncryptParams) (Ciphertext, DecryptParams, error) {
	padding := aes.BlockSize - len(plaintext)%aes.BlockSize
	padtext := string(bytes.Repeat([]byte{byte(padding)}, padding))
	plaintext = plaintext + padtext

	key, err := localKey()
	if err != nil {
		return "", nil, fmt.Errorf("Error retrieving local key: %s", err)
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return "", nil, fmt.Errorf("Error creating AES cipher: %s", err)
	}

	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return "", nil, fmt.Errorf("Error initializing IV: %s", err)
	}

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext[aes.BlockSize:], []byte(plaintext))

	b64Ciphertext := base64.StdEncoding.EncodeToString(ciphertext)
	return Ciphertext(b64Ciphertext), nil, nil
}

作者:pa00102    项目:refle   
// AES-CBC 返回binary结果
func AESCBC(byteKey, src []byte, isEncode bool) (rst []byte) {
	rst = make([]byte, len(src))
	b, err := aes.NewCipher(byteKey)
	if err != nil {
		return
	}
	iv := byteKey[:aes.BlockSize]
	var cc cipher.BlockMode
	var nsrc []byte
	if isEncode {
		cc = cipher.NewCBCEncrypter(b, iv)
		nsrc = PKCS5Padding(src, aes.BlockSize)
	} else {
		cc = cipher.NewCBCDecrypter(b, iv)
		nsrc = src
	}
	dst := make([]byte, len(nsrc))
	cc.CryptBlocks(dst, nsrc)
	if isEncode {
		rst = dst
	} else {
		rst = PKCS5UnPadding(dst)
	}
	return
}

作者:JonathanLoga    项目:mut   
// AES256CBCEncrypt encrypts the given plaintext with AES-256 in CBC mode.
// The supplied key must be 32 bytes long.
// The returned ciphertext is prepended by a randomly generated IV.
func AES256CBCEncrypt(key, plaintext []byte, rand io.Reader) (ciphertext []byte) {
	if len(key) != 32 {
		panic(log.Critical("cipher: AES-256 key is not 32 bytes long"))
	}
	block, _ := aes.NewCipher(key) // correct key length was enforced above

	// CBC mode works on blocks so plaintexts may need to be padded to the
	// next whole block. For an example of such padding, see
	// https://tools.ietf.org/html/rfc5246#section-6.2.3.2. Here we'll
	// assume that the plaintext is already of the correct length.
	if len(plaintext)%aes.BlockSize != 0 {
		panic(log.Critical("cipher: plaintext is not a multiple of the block size"))
	}

	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	ciphertext = make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	_, err := io.ReadFull(rand, iv)
	if err != nil {
		panic(log.Critical(err))
	}

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)

	return
}

作者:tcnks    项目:go-crypt   
func main() {
	plainText := []byte("Bob loves Alice.")
	key := []byte("passw0rdpassw0rdpassw0rdpassw0rd")

	// Create new AES cipher block
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Printf("err: %s\n", err)
	}

	// The IV (Initialization Vector) need to be unique, but not secure.
	// Therefore, it's common to include it at the beginning of the cipher text.
	cipherText := make([]byte, aes.BlockSize+len(plainText))

	// Fill iv with rand value
	iv := cipherText[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		fmt.Printf("err: %s\n", err)
	}

	// Encrypt
	encryptMode := cipher.NewCBCEncrypter(block, iv)
	encryptMode.CryptBlocks(cipherText[aes.BlockSize:], plainText)
	fmt.Printf("Cipher text: %v\n", cipherText)

	// Decrypt
	decryptedText := make([]byte, len(cipherText[aes.BlockSize:]))
	decryptMode := cipher.NewCBCDecrypter(block, cipherText[:aes.BlockSize])
	decryptMode.CryptBlocks(decryptedText, cipherText[aes.BlockSize:])
	fmt.Printf("Decrypted text: %s\n", string(decryptedText))
}


问题


面经


文章

微信
公众号

扫码关注公众号