Exemplo n.º 1
0
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)
	}
}
Exemplo n.º 2
0
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
}
Exemplo n.º 3
0
Arquivo: aes_gcm.go Projeto: bndw/pick
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
}
Exemplo n.º 4
0
Arquivo: aes_gcm.go Projeto: bndw/pick
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
}
Exemplo n.º 5
0
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
}
Exemplo n.º 6
0
// 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
}
Exemplo n.º 7
0
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
}
Exemplo n.º 8
0
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
}
Exemplo n.º 9
0
// 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
}
Exemplo n.º 10
0
// 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
}
Exemplo n.º 11
0
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
}
Exemplo n.º 12
0
// 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
}
Exemplo n.º 13
0
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
}
Exemplo n.º 14
0
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
}
Exemplo n.º 15
0
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_))
}
Exemplo n.º 16
0
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))
}
Exemplo n.º 17
0
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
}
Exemplo n.º 18
0
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))

}
Exemplo n.º 19
0
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
}
Exemplo n.º 20
0
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)
}
Exemplo n.º 21
0
func TestTagFailureOverwrite(t *testing.T) {
	// The AESNI GCM code decrypts and authenticates concurrently and so
	// overwrites the output buffer before checking the authentication tag.
	// In order to be consistent across platforms, all implementations
	// should do this and this test checks that.

	key, _ := hex.DecodeString("ab72c77b97cb5fe9a382d9fe81ffdbed")
	nonce, _ := hex.DecodeString("54cc7dc2c37ec006bcc6d1db")
	ciphertext, _ := hex.DecodeString("0e1bde206a07a9c2c1b65300f8c649972b4401346697138c7a4891ee59867d0c")

	aes, _ := aes.NewCipher(key)
	aesgcm, _ := cipher.NewGCM(aes)

	dst := make([]byte, len(ciphertext)-16)
	for i := range dst {
		dst[i] = 42
	}

	result, err := aesgcm.Open(dst[:0], nonce, ciphertext, nil)
	if err == nil {
		t.Fatal("Bad Open still resulted in nil error.")
	}

	if result != nil {
		t.Fatal("Failed Open returned non-nil result.")
	}

	for i := range dst {
		if dst[i] != 0 {
			t.Fatal("Failed Open didn't zero dst buffer")
		}
	}
}
Exemplo n.º 22
0
func NewCryptFS(key []byte, useOpenssl bool) *CryptFS {

	if len(key) != KEY_LEN {
		panic(fmt.Sprintf("Unsupported key length %d", len(key)))
	}

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

	var gcm cipher.AEAD
	if useOpenssl {
		gcm = opensslGCM{key}
	} else {
		gcm, err = cipher.NewGCM(b)
		if err != nil {
			panic(err)
		}
	}

	cipherBS := DEFAULT_PLAINBS + NONCE_LEN + AUTH_TAG_LEN

	return &CryptFS{
		blockCipher:  b,
		gcm:          gcm,
		plainBS:      DEFAULT_PLAINBS,
		cipherBS:     uint64(cipherBS),
		allZeroBlock: make([]byte, cipherBS),
	}
}
Exemplo n.º 23
0
func (se *stateEncryptorImpl) init(node *nodeImpl, stateKey, nonceStateKey, deployTxKey, invokeTxNonce []byte) error {
	// Initi fields
	se.counter = 0
	se.node = node
	se.stateKey = stateKey
	se.nonceStateKey = nonceStateKey
	se.deployTxKey = deployTxKey
	se.invokeTxNonce = invokeTxNonce

	// Init aes
	c, err := aes.NewCipher(se.stateKey)
	if err != nil {
		return err
	}

	// Init gcm for encryption
	se.gcmEnc, err = cipher.NewGCM(c)
	if err != nil {
		return err
	}

	// Init nonce size
	se.nonceSize = se.gcmEnc.NonceSize()
	return nil
}
Exemplo n.º 24
0
// Init initializes this cipher with the passed parameters
func (sc *aes256GCMStreamCipherImpl) Init(forEncryption bool, params primitives.CipherParameters) error {
	var aesKey *aesSecretKeyImpl

	switch sk := params.(type) {
	case *aesSecretKeyImpl:
		if len(sk.key) != 32 {
			return fmt.Errorf("Invalid key lentgh. Len was [%d], expected [32].", len(sk.key))
		}
		aesKey = sk
	default:
		return primitives.ErrInvalidSecretKeyType
	}

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

	// Init gcm for encryption
	sc.gcm, err = cipher.NewGCM(c)
	if err != nil {
		return err
	}

	sc.forEncryption = forEncryption
	sc.nonceSize = sc.gcm.NonceSize()

	return nil
}
Exemplo n.º 25
0
func ExampleNewGCM_decrypt() {
	// 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("1019aa66cd7c024f9efd0038899dae1973ee69427f5a6579eba292ffe1b5a260")

	nonce, _ := hex.DecodeString("37b8e8a308c354048d245f6d")

	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", plaintext)
	// Output: exampleplaintext
}
Exemplo n.º 26
0
func (c *AEAD) Decrypt(ciphertext string) ([]byte, error) {
	if len(c.Key) < 32 {
		return []byte{}, errors.Errorf("Key must be longer 32 bytes, got %d bytes", len(c.Key))
	}

	raw, err := base64.URLEncoding.DecodeString(ciphertext)
	if err != nil {
		return []byte{}, errors.New(err)
	}

	n := len(raw)
	block, err := aes.NewCipher(c.Key)
	if err != nil {
		return []byte{}, errors.New(err)
	}

	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		return []byte{}, errors.New(err)
	}

	plaintext, err := aesgcm.Open(nil, raw[n-12:n], raw[:n-12], nil)
	if err != nil {
		return []byte{}, errors.New(err)
	}

	return plaintext, nil
}
Exemplo n.º 27
0
func (c *AEAD) Encrypt(plaintext []byte) (string, error) {
	// The key argument should be the AES key, either 16 or 32 bytes
	// to select AES-128 or AES-256.
	if len(c.Key) < 32 {
		return "", errors.Errorf("Key must be longer 32 bytes, got %d bytes", len(c.Key))
	}

	block, err := aes.NewCipher(c.Key[:32])
	if err != nil {
		return "", errors.New(err)
	}

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

	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		return "", errors.New(err)
	}

	ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
	return base64.URLEncoding.EncodeToString(append(ciphertext, nonce...)), nil
}
Exemplo n.º 28
0
// encrypts the given plaintext with the given key.
// It returns a base64-encoded string consisting of the nonce + aad + encryptedBytes
// Each piece is a single space delimited.
func AesEncrypt(secretKey []byte, plaintext []byte) (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())
	}

	nonce := make([]byte, gcm.NonceSize())
	if _, err := rand.Read(nonce); err != nil {
		log.Fatal("Error generating AES nonce" + err.Error())
	}

	aad := make([]byte, 12)
	if _, err := rand.Read(aad); err != nil {
		log.Fatal("Error generating AES AAD" + err.Error())
	}

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

	var buffer bytes.Buffer
	buffer.WriteString(base64.StdEncoding.EncodeToString(nonce))
	buffer.WriteString(aesDelimiter)
	buffer.WriteString(base64.StdEncoding.EncodeToString(aad))
	buffer.WriteString(aesDelimiter)
	buffer.WriteString(base64.StdEncoding.EncodeToString(ciphertext))

	return buffer.String(), nil
}
Exemplo n.º 29
0
// goGCMWrapper - This wrapper makes sure gocryptfs can be compiled on Go
// versions 1.4 and lower that lack NewGCMWithNonceSize().
// 128 bit GCM IVs will not work when using built-in Go crypto, obviously, when
// compiled on 1.4.
func goGCMWrapper(bc cipher.Block, nonceSize int) (cipher.AEAD, error) {
	if nonceSize != 12 {
		Warn.Printf("128 bit GCM IVs are not supported by Go 1.4 and lower.\n")
		Warn.Printf("Please use openssl crypto or recompile using a newer Go runtime.\n")
		return nil, fmt.Errorf("128 bit GCM IVs are not supported by Go 1.4 and lower")
	}
	return cipher.NewGCM(bc)
}
Exemplo n.º 30
0
func makeAESGCM(aesKey []byte) (cipher.AEAD, error) {
	blockCipher, err := aes.NewCipher(aesKey)
	if err != nil {
		return nil, err
	}

	return cipher.NewGCM(blockCipher)
}