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


Golang cipher.NewGCM函數代碼示例

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


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


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