• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang cipher.NewGCM函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中crypto/cipher.NewGCM函数的典型用法代码示例。如果您正苦于以下问题:Golang NewGCM函数的具体用法?Golang NewGCM怎么用?Golang NewGCM使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewGCM函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: SetDefaultSecretKey

func SetDefaultSecretKey(method string, key string) {
	secretKey = []byte(key)
	if len(secretKey) > 32 {
		secretKey = secretKey[0:32]
	} else {
		tmp := make([]byte, 32)
		copy(tmp[0:len(secretKey)], secretKey)
	}
	copy(salsa20Key[:], secretKey[:32])
	aesblock, _ := aes.NewCipher(secretKey)
	aes256gcm, _ = cipher.NewGCM(aesblock)
	defaultEncryptMethod = Salsa20Encrypter
	if strings.EqualFold(method, "rc4") {
		defaultEncryptMethod = RC4Encrypter
	} else if strings.EqualFold(method, "salsa20") {
		defaultEncryptMethod = Salsa20Encrypter
	} else if strings.EqualFold(method, "aes") {
		defaultEncryptMethod = AES256Encrypter
	} else if strings.EqualFold(method, "chacha20") {
		defaultEncryptMethod = Chacha20Encrypter
	} else if strings.EqualFold(method, "none") {
		defaultEncryptMethod = 0
	} else if strings.EqualFold(method, "auto") {
		if strings.Contains(runtime.GOARCH, "386") || strings.Contains(runtime.GOARCH, "amd64") {
			defaultEncryptMethod = AES256Encrypter
		} else if strings.Contains(runtime.GOARCH, "arm") {
			defaultEncryptMethod = Chacha20Encrypter
		}
		//log.Printf("Auto select fastest encrypt method:%d", defaultEncryptMethod)
	}
}
开发者ID:yinqiwen,项目名称:gsnova,代码行数:31,代码来源:event.go


示例2: Decrypt

func (se *queryStateEncryptor) Decrypt(raw []byte) ([]byte, error) {
	if len(raw) <= utils.NonceSize {
		return nil, utils.ErrDecrypt
	}

	// raw consists of (txNonce, ct)
	txNonce := raw[:utils.NonceSize]
	//	se.log.Info("Decrypting with txNonce  ", utils.EncodeBase64(txNonce))
	ct := raw[utils.NonceSize:]

	nonce := make([]byte, se.nonceSize)
	copy(nonce, ct)

	key := utils.HMACTruncated(se.deployTxKey, append([]byte{3}, txNonce...), utils.AESKeyLength)
	//	se.log.Info("Decrypting with key  ", utils.EncodeBase64(key))
	c, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	gcm, err := cipher.NewGCM(c)
	if err != nil {
		return nil, err
	}

	se.nonceSize = se.gcmEnc.NonceSize()

	out, err := gcm.Open(nil, nonce, ct[se.nonceSize:], txNonce)
	if err != nil {
		return nil, utils.ErrDecrypt
	}
	return out, nil
}
开发者ID:butine,项目名称:research,代码行数:33,代码来源:validator_chain.go


示例3: Decrypt

func (c *AESGCMClient) Decrypt(data []byte, password []byte) (plaintext []byte, err error) {
	var store AESGCMStore
	if err := json.Unmarshal(data, &store); err != nil {
		return nil, err
	}

	key, err := c.deriveKeyWithSalt(password, store.Salt, c.keyLen())
	if err != nil {
		return
	}

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

	gcm, err := cipher.NewGCM(ac)
	if err != nil {
		return
	}

	plaintext, err = gcm.Open(nil, store.Nonce, store.Ciphertext, nil)
	if err != nil {
		return nil, &errors.SafeDecryptionFailed{}
	}

	return
}
开发者ID:bndw,项目名称:pick,代码行数:28,代码来源:aes_gcm.go


示例4: Encrypt

func (c *AESGCMClient) Encrypt(plaintext []byte, password []byte) (data []byte, err error) {
	key, salt, err := c.deriveKey(password, c.keyLen())
	if err != nil {
		return
	}

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

	gcm, err := cipher.NewGCM(ac)
	if err != nil {
		return
	}

	nonce := make([]byte, gcm.NonceSize())
	if _, err = rand.Read(nonce); err != nil {
		return
	}

	ciphertext := gcm.Seal(nil, nonce, plaintext, nil)

	store := AESGCMStore{
		Salt:       salt,
		Nonce:      nonce,
		Ciphertext: ciphertext,
	}
	data, err = json.Marshal(store)
	if err != nil {
		return
	}

	return
}
开发者ID:bndw,项目名称:pick,代码行数:35,代码来源:aes_gcm.go


示例5: LoadCipher

func LoadCipher(key, nonce []byte) (*Cipher, error) {
	if len(key) != aes.BlockSize {
		return nil, errors.New("Invalid key.")
	}

	if len(nonce) < 12 {
		return nil, errors.New("Invalid nonce.")
	}

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

	aead, err := gocipher.NewGCM(block)
	if err != nil {
		return nil, err
	}

	nonceInt := big.NewInt(0)
	nonceInt.SetBytes(nonce)

	return &Cipher{
		aead:  aead,
		nonce: nonceInt,
	}, nil
}
开发者ID:schmich,项目名称:ward,代码行数:27,代码来源:crypto.go


示例6: decryptPayload

// decryptPayload is used to decrypt a message with a given key,
// and verify it's contents. Any padding will be removed, and a
// slice to the plaintext is returned. Decryption is done IN PLACE!
func decryptPayload(key []byte, msg []byte, data []byte) ([]byte, error) {
	// Ensure the length is sane
	if len(msg) <= encryptedLength(0) {
		return nil, fmt.Errorf("Payload is too small to decrypt")
	}

	// Verify the version
	if msg[0] != encryptionVersion {
		return nil, fmt.Errorf("Unsupported encryption version %d", msg[0])
	}

	// Get the AES block cipher
	aesBlock, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	// Get the GCM cipher mode
	gcm, err := cipher.NewGCM(aesBlock)
	if err != nil {
		return nil, err
	}

	// Decrypt the message
	nonce := msg[versionSize : versionSize+nonceSize]
	ciphertext := msg[versionSize+nonceSize:]
	plain, err := gcm.Open(nil, nonce, ciphertext, data)
	if err != nil {
		return nil, err
	}

	// Remove the PKCS7 padding
	return pkcs7decode(plain, aes.BlockSize), nil
}
开发者ID:kainosnoema,项目名称:memberlist,代码行数:37,代码来源:security.go


示例7: EncryptFile

func EncryptFile(filepath string, destination string, users ...User) (err error) {

	// Current structure of the final ciphertext:
	// [ num of user tokens (8B) | ... user token(s) ... | nonce (12B) | ciphertext (variable length) ]

	var plaintext []byte
	var block cipher.Block

	// Open the file to be encrypted (the plaintext)
	if plaintext, err = ioutil.ReadFile(filepath); err != nil {
		return err
	}

	// Generate a symmetric AES-256 key
	symkey, err := genSymmetricKey()
	if err != nil {
		return err
	}

	// Generate token(s) for the key
	tokens, err := prepTokens(symkey, users...)
	if err != nil {
		return err
	}

	// Write 8 bytes for the size of the tokens
	tokens_size := make([]byte, 8)
	_ = binary.PutUvarint(tokens_size, uint64(len(tokens)))

	ciphertext := append(tokens_size, tokens...)

	// Create the AES cipher block from the key
	if block, err = aes.NewCipher(symkey); err != nil {
		return err
	}

	// Init a GCM (Galois/Counter Mode) encrypter from the AES cipher.
	encrypter, err := cipher.NewGCM(block)
	if err != nil {
		return err
	}

	// Create a nonce (random data used in the encryption process).
	// The nonce used in encryption must be the same used in the
	// decryption process. Append it to ciphertext
	nonce := make([]byte, encrypter.NonceSize())
	if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
		return err
	}
	ciphertext = append(ciphertext, nonce...)

	// Seal appends the encrypted authenticated plaintext to ciphertext.
	// The nil value is optional data which is not being used currently.
	ciphertext = encrypter.Seal(ciphertext, nonce, plaintext, nil)

	// Write ciphertext to destination with permissions 0777
	ioutil.WriteFile(destination, ciphertext, 0777)

	return nil
}
开发者ID:CPSSD,项目名称:MDFS,代码行数:60,代码来源:file_lock.go


示例8: DecryptQueryResult

func (client *clientImpl) DecryptQueryResult(queryTx *obc.Transaction, ct []byte) ([]byte, error) {
	queryKey := utils.HMACTruncated(client.node.enrollChainKey, append([]byte{6}, queryTx.Nonce...), utils.AESKeyLength)
	//	client.node.log.Info("QUERY Decrypting with key: ", utils.EncodeBase64(queryKey))

	if len(ct) <= utils.NonceSize {
		return nil, utils.ErrDecrypt
	}

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

	gcm, err := cipher.NewGCM(c)
	if err != nil {
		return nil, err
	}

	nonce := make([]byte, gcm.NonceSize())
	copy(nonce, ct)

	out, err := gcm.Open(nil, nonce, ct[gcm.NonceSize():], nil)
	if err != nil {
		client.node.log.Error("Failed decrypting query result [%s].", err.Error())
		return nil, utils.ErrDecrypt
	}
	return out, nil
}
开发者ID:masterDev1985,项目名称:obc-peer,代码行数:28,代码来源:client_impl.go


示例9: Decrypt

// Decrypt decrypts the given ciphertext with the given key k.
func Decrypt(k, ciphertext []byte) ([]byte, error) {
	// Decrypt ciphertext
	block, err := aes.NewCipher(k)
	if err != nil {
		return nil, err
	}

	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}

	ns := gcm.NonceSize()

	// Validate data
	if len(ciphertext) < ns {
		return nil, errors.New("Ciphertext is too short")
	}

	nonce := ciphertext[:ns]
	ciphertext = ciphertext[ns:]
	plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
	if err != nil {
		return nil, err
	}

	return plaintext, nil
}
开发者ID:writeas,项目名称:web-core,代码行数:29,代码来源:data.go


示例10: Encrypt

// Encrypt AES-encrypts given text with the given key k.
// This is used for encrypting sensitive information in the database, such as
// oAuth tokens and email addresses.
func Encrypt(k []byte, text string) ([]byte, error) {
	// Validate parameters
	if len(k) != keyLen {
		return nil, errors.New(fmt.Sprintf("Invalid key length (must be %d bytes).", keyLen))
	}

	// Encrypt plaintext with AES-GCM
	block, err := aes.NewCipher(k)
	if err != nil {
		return nil, err
	}

	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}

	// Generate nonce
	ns := gcm.NonceSize()
	nonce := make([]byte, ns)
	if _, err := rand.Read(nonce); err != nil {
		return nil, err
	}

	ciphertext := gcm.Seal(nil, nonce, []byte(text), nil)

	// Build text output in the format:
	// NonceCiphertext
	outtext := append(nonce, ciphertext...)

	return outtext, nil
}
开发者ID:writeas,项目名称:web-core,代码行数:35,代码来源:data.go


示例11: AesDecrypt

func AesDecrypt(secretKey []byte, base64EncryptedText string) (string, error) {
	aesCipher, err := aes.NewCipher(secretKey)
	if err != nil {
		log.Fatal("Error creating AES cipher" + err.Error())
	}

	gcm, err := cipher.NewGCM(aesCipher)
	if err != nil {
		log.Fatal("Error creating GCM cipher" + err.Error())
	}

	sections := strings.Split(base64EncryptedText, aesDelimiter)

	nonce, err := base64.StdEncoding.DecodeString(sections[0])
	if err != nil {
		log.Fatal("Error decoding nonce" + err.Error())
	}

	aad, err := base64.StdEncoding.DecodeString(sections[1])
	if err != nil {
		log.Fatal("Error decoding AAD" + err.Error())
	}

	ciphertext, err := base64.StdEncoding.DecodeString(sections[2])
	if err != nil {
		log.Fatal("Error decoding ciphertext" + err.Error())
	}

	plaintextBytes, err := gcm.Open(nil, nonce, ciphertext, aad)
	if err != nil {
		log.Fatal("Error decrypting ciphertext" + err.Error())
	}

	return string(plaintextBytes[:]), nil
}
开发者ID:gravieinc,项目名称:aws-crypto-tools-go,代码行数:35,代码来源:aes.go


示例12: NewNonceService

// NewNonceService constructs a NonceService with defaults
func NewNonceService(scope metrics.Scope) (*NonceService, error) {
	scope = scope.NewScope("NonceService")
	key := make([]byte, 16)
	if _, err := rand.Read(key); err != nil {
		return nil, err
	}

	c, err := aes.NewCipher(key)
	if err != nil {
		panic("Failure in NewCipher: " + err.Error())
	}
	gcm, err := cipher.NewGCM(c)
	if err != nil {
		panic("Failure in NewGCM: " + err.Error())
	}

	return &NonceService{
		earliest: 0,
		latest:   0,
		used:     make(map[int64]bool, MaxUsed),
		gcm:      gcm,
		maxUsed:  MaxUsed,
		stats:    scope,
	}, nil
}
开发者ID:jfrazelle,项目名称:boulder,代码行数:26,代码来源:nonce.go


示例13: aesDecrypt

func (e *enc) aesDecrypt(key, message []byte) ([]byte, error) {
	if len(message) <= NonceSize {
		return nil, errors.New("Message is too short")
	}

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

	gcm, err := cipher.NewGCM(c)
	if err != nil {
		return nil, err
	}

	nonce := make([]byte, NonceSize)
	copy(nonce, message)

	out, err := gcm.Open(nil, nonce, message[NonceSize:], nil)
	if err != nil {
		fmt.Println("this err")
		return nil, err
	}
	return out, nil
}
开发者ID:lstoll,项目名称:simplevault,代码行数:25,代码来源:enc.go


示例14: Decrypt

func (alg *AesGcm) Decrypt(aad, cek, iv, cipherText, authTag []byte) (plainText []byte, err error) {

	cekSizeBits := len(cek) << 3

	if cekSizeBits != alg.keySizeBits {
		return nil, errors.New(fmt.Sprintf("AesGcm.Decrypt(): expected key of size %v bits, but was given %v bits.", alg.keySizeBits, cekSizeBits))
	}

	var block cipher.Block

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

	var aesgcm cipher.AEAD

	if aesgcm, err = cipher.NewGCM(block); err != nil {
		return nil, err
	}

	cipherWithTag := append(cipherText, authTag...)

	if plainText, err = aesgcm.Open(nil, iv, cipherWithTag, aad); err != nil {
		return nil, err
	}

	return plainText, nil
}
开发者ID:useidel,项目名称:notary,代码行数:28,代码来源:aes_gcm.go


示例15: 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)
		return
	}

	aead, err := cipher.NewGCM(block)
	if err != nil {
		fmt.Printf("err: %s\n", err)
		return
	}

	fmt.Println(aead.NonceSize())
	nonce := make([]byte, aead.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		fmt.Printf("err: %s\n", err)
		return
	}

	cipherText := aead.Seal(nil, nonce, plainText, nil)
	fmt.Printf("Cipher text: %x\n", cipherText)

	plainText_, err := aead.Open(nil, nonce, cipherText, nil)
	if err != nil {
		fmt.Printf("err: %s\n", err)
		return
	}
	fmt.Printf("Decrypted text: %s\n", string(plainText_))
}
开发者ID:tcnksm,项目名称:go-crypto,代码行数:34,代码来源:main.go


示例16: ExampleNewGCMDecrypter

func ExampleNewGCMDecrypter() {
	// The key argument should be the AES key, either 16 or 32 bytes
	// to select AES-128 or AES-256.
	key := []byte("AES256Key-32Characters1234567890")
	ciphertext, _ := hex.DecodeString("f90fbef747e7212ad7410d0eee2d965de7e890471695cddd2a5bc0ef5da1d04ad8147b62141ad6e4914aee8c512f64fba9037603d41de0d50b718bd665f019cdcd")

	nonce, _ := hex.DecodeString("bb8ef84243d2ee95a41c6c57")

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

	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		panic(err.Error())
	}

	plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
	if err != nil {
		panic(err.Error())
	}

	fmt.Printf("%s\n", string(plaintext))
}
开发者ID:kelur-hawkingrei,项目名称:learning-golang,代码行数:25,代码来源:main.go


示例17: Encrypt

func (alg *AesGcm) 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("AesGcm.Encrypt(): expected key of size %v bits, but was given %v bits.", alg.keySizeBits, cekSizeBits))
	}

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

	var block cipher.Block

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

	var aesgcm cipher.AEAD

	if aesgcm, err = cipher.NewGCM(block); err != nil {
		return nil, nil, nil, err
	}

	cipherWithTag := aesgcm.Seal(nil, iv, plainText, aad)

	cipherText = cipherWithTag[:len(cipherWithTag)-aesgcm.Overhead()]
	authTag = cipherWithTag[len(cipherWithTag)-aesgcm.Overhead():]

	return iv, cipherText, authTag, nil
}
开发者ID:useidel,项目名称:notary,代码行数:31,代码来源:aes_gcm.go


示例18: main

func main() {
	key := []byte("AES256Key-32Characters1234567890")
	plaintext := []byte("exampleplaintext")
	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err.Error())
	}
	nonce := make([]byte, 12)
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		panic(err.Error())
	}
	//fmt.Printf("%s\n", string(nonce))
	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		panic(err.Error())
	}
	ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
	fmt.Printf("%x\n", ciphertext)
	newplaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
	if err != nil {
		panic(err.Error())
	}

	fmt.Printf("%s\n", string(newplaintext))

}
开发者ID:kelur-hawkingrei,项目名称:learning-golang,代码行数:26,代码来源:main.go


示例19: DecryptWithID

func DecryptWithID(message []byte) ([]byte, error) {
	if len(message) <= NonceSize+4 {
		return nil, ErrDecrypt
	}

	id := binary.BigEndian.Uint32(message[:4])
	key, ok := SelectKeyForID(id)
	if !ok {
		return nil, ErrDecrypt
	}

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

	gcm, err := cipher.NewGCM(c)
	if err != nil {
		return nil, ErrDecrypt
	}

	nonce := make([]byte, NonceSize)
	copy(nonce, message[4:])

	// Decrypt the message, using the sender ID as the additional
	// data requiring authentication.
	out, err := gcm.Open(nil, nonce, message[4+NonceSize:], message[:4])
	if err != nil {
		return nil, ErrDecrypt
	}
	return out, nil
}
开发者ID:jmptrader,项目名称:gocrypto,代码行数:32,代码来源:secret_test.go


示例20: ExampleNewGCMEncrypter

func ExampleNewGCMEncrypter() {
	// The key argument should be the AES key, either 16 or 32 bytes
	// to select AES-128 or AES-256.
	key := []byte("AES256Key-32Characters1234567890")
	plaintext := []byte("exampleplaintext")

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

	// Never use more than 2^32 random nonces with a given key because of the risk of a repeat.
	nonce := make([]byte, 12)

	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		panic(err.Error())
	}
	fmt.Print(nonce)
	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		panic(err.Error())
	}

	ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
	fmt.Printf("%x\n", ciphertext)
}
开发者ID:kelur-hawkingrei,项目名称:learning-golang,代码行数:26,代码来源:main.go



注:本文中的crypto/cipher.NewGCM函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang cipher.NewOFB函数代码示例发布时间:2022-05-24
下一篇:
Golang cipher.NewCTR函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap