本文整理汇总了Golang中crypto/cipher.NewCBCEncrypter函数的典型用法代码示例。如果您正苦于以下问题:Golang NewCBCEncrypter函数的具体用法?Golang NewCBCEncrypter怎么用?Golang NewCBCEncrypter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewCBCEncrypter函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: Encrypt
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
}
开发者ID:acasajus,项目名称:dkeyczar,代码行数:25,代码来源:aes_key.go
示例17: Encrypt
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
}
开发者ID:Zemanta,项目名称:go-secretcrypt,代码行数:27,代码来源:local.go
示例18: AESCBC
// 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
}
开发者ID:pa001024,项目名称:reflex,代码行数:26,代码来源:util.crypto.go
示例19: AES256CBCEncrypt
// 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
}
开发者ID:JonathanLogan,项目名称:mute,代码行数:31,代码来源:aes256.go
示例20: main
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))
}
开发者ID:tcnksm,项目名称:go-crypto,代码行数:31,代码来源:main.go
注:本文中的crypto/cipher.NewCBCEncrypter函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论