當前位置: 首頁>>代碼示例>>Golang>>正文


Golang cipher.NewCBCEncrypter函數代碼示例

本文整理匯總了Golang中crypto/cipher.NewCBCEncrypter函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewCBCEncrypter函數的具體用法?Golang NewCBCEncrypter怎麽用?Golang NewCBCEncrypter使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NewCBCEncrypter函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: buildMasterKey

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
}
開發者ID:postfix,項目名稱:gokeepasslib,代碼行數:29,代碼來源:credentials.go

示例2: Sign

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
}
開發者ID:JFHSebastian,項目名稱:gokerb,代碼行數:57,代碼來源:crypto.go

示例3: encryptAES

// 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
}
開發者ID:mohoff,項目名稱:CryptoWrapper,代碼行數:36,代碼來源:aes.go

示例4: get

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)

}
開發者ID:Cergoo,項目名稱:ercaptcha,代碼行數:35,代碼來源:main.go

示例5: ExampleNewCBCEncrypter

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)
}
開發者ID:RajibTheKing,項目名稱:gcc,代碼行數:34,代碼來源:example_test.go

示例6: AESEncryptMsg

// 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
}
開發者ID:jsix,項目名稱:wechat,代碼行數:36,代碼來源:aes_crypto.go

示例7: encrypt

// 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
}
開發者ID:trigrass2,項目名稱:wechat_component,代碼行數:30,代碼來源:cipher.go

示例8: TestCBC_AES

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)
		}
	}
}
開發者ID:kostyll,項目名稱:gccpy,代碼行數:25,代碼來源:cbc_aes_test.go

示例9: NewAesCBCCrypter

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
}
開發者ID:Andals,項目名稱:gobox,代碼行數:25,代碼來源:aes.go

示例10: EncryptFilename

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
}
開發者ID:Lennix,項目名稱:syncthing,代碼行數:35,代碼來源:encryption.go

示例11: Encrypt

// 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])
}
開發者ID:majestrate,項目名稱:go-i2p,代碼行數:8,代碼來源:tunnel.go

示例12: EncryptShimTicket

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)
}
開發者ID:caiolima,項目名稱:webkit,代碼行數:31,代碼來源:shim_ticket.go

示例13: Seal

// 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
}
開發者ID:lestrrat,項目名稱:go-jwx,代碼行數:26,代碼來源:aescbc.go

示例14: Encrypt

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
}
開發者ID:useidel,項目名稱:notary,代碼行數:30,代碼來源:aes_cbc_hmac.go

示例15: Encrypt

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
}
開發者ID:pombredanne,項目名稱:snp,代碼行數:29,代碼來源:crypto.go


注:本文中的crypto/cipher.NewCBCEncrypter函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。