// EasySeal encrypts message using key. A 24-byte nonce is generated and
// prepended to the output. The key and nonce pair must be unique for each
// distinct message, and the output will be Overhead+24 bytes longer than
// message.
969465
func EasySeal(message []byte, key nacl.Key) []byte {
	nonce := nacl.NewNonce()
	return Seal(nonce[:], message, nonce, key)
}
1366327
func (e CBC) Encrypt(key interface{}, plaintext []byte) (*etree.Element, error) {
	keyBuf, ok := key.([]byte)
	if !ok {
		return nil, ErrIncorrectKeyType("[]byte")
	}
	if len(keyBuf) != e.keySize {
		return nil, ErrIncorrectKeyLength(e.keySize)
	}

	block, err := e.cipher(keyBuf)
	if err != nil {
		return nil, err
	}

	encryptedDataEl := etree.NewElement("xenc:EncryptedData")
	encryptedDataEl.CreateAttr("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#")
	{
		randBuf := make([]byte, 16)
		if _, err := RandReader.Read(randBuf); err != nil {
			return nil, err
		}
		encryptedDataEl.CreateAttr("Id", fmt.Sprintf("_%x", randBuf))
	}

	em := encryptedDataEl.CreateElement("xenc:EncryptionMethod")
	em.CreateAttr("Algorithm", e.algorithm)
	em.CreateAttr("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#")

	plaintext = appendPadding(plaintext, block.BlockSize())

	iv := make([]byte, block.BlockSize())
	if _, err := RandReader.Read(iv); err != nil {
		return nil, err
	}

	mode := cipher.NewCBCEncrypter(block, iv)
	ciphertext := make([]byte, len(plaintext))
	mode.CryptBlocks(ciphertext, plaintext)
	ciphertext = append(iv, ciphertext...)

	cd := encryptedDataEl.CreateElement("xenc:CipherData")
	cd.CreateAttr("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#")
	cd.CreateElement("xenc:CipherValue").SetText(base64.StdEncoding.EncodeToString(ciphertext))
	return encryptedDataEl, nil
}
325382
func (key ObjectKey) Seal(extKey, iv [32]byte, domain, bucket, object string) SealedKey {
	var (
		sealingKey   [32]byte
		encryptedKey bytes.Buffer
	)
	mac := hmac.New(sha256.New, extKey[:])
	mac.Write(iv[:])
	mac.Write([]byte(domain))
	mac.Write([]byte(SealAlgorithm))
	mac.Write([]byte(path.Join(bucket, object))) // use path.Join for canonical 'bucket/object'
	mac.Sum(sealingKey[:0])
	if n, err := sio.Encrypt(&encryptedKey, bytes.NewReader(key[:]), sio.Config{Key: sealingKey[:]}); n != 64 || err != nil {
		logger.CriticalIf(context.Background(), errors.New("Unable to generate sealed key"))
	}
	sealedKey := SealedKey{
		IV:        iv,
		Algorithm: SealAlgorithm,
	}
	copy(sealedKey.Key[:], encryptedKey.Bytes())
	return sealedKey
}
1230147
func (d RSAOAEPKeyDecrypt) KeyDecrypt(enckey []byte) ([]byte, error) {
	if debug.Enabled {
		debug.Printf("START OAEP.KeyDecrypt")
	}
	var hash hash.Hash
	switch d.alg {
	case jwa.RSA_OAEP:
		hash = sha1.New()
	case jwa.RSA_OAEP_256:
		hash = sha256.New()
	default:
		return nil, errors.New("failed to generate key encrypter for RSA-OAEP: RSA_OAEP/RSA_OAEP_256 required")
	}
	return rsa.DecryptOAEP(hash, rand.Reader, d.privkey, enckey, []byte{})
}
35634
func SealWhole(plaintext []byte, encKey SecretboxKey, signKey SignKey, signaturePrefix kbcrypto.SignaturePrefix, nonce Nonce) []byte {
	encoder := NewEncoder(encKey, signKey, signaturePrefix, nonce)
	output := encoder.Write(plaintext)
	output = append(output, encoder.Finish()...)
	return output
}
689515
func EncryptArmor62Seal(version Version, plaintext []byte, sender BoxSecretKey, receivers []BoxPublicKey, brand string) (string, error) {
	ephemeralKeyCreator, err := receiversToEphemeralKeyCreator(receivers)
	if err != nil {
		return "", err
	}
	return encryptArmor62Seal(version, plaintext, sender, receivers, ephemeralKeyCreator, defaultEncryptRNG{}, brand)
}
1249477
func Aes256ECBDecrypt(key [32]byte, ciphertext []byte) (plaintext []byte, err error) {
	return aesECBDec(key[:], ciphertext)
}
394178
func Encrypt(key *Key, passphrase []byte) []byte {
	dst := make([]byte, EncryptedKeyLength)
	copy(dst[0:32], key[:])

	h := hashKey(key[:])
	copy(dst[32:36], h)

	k, err := scrypt.Key(passphrase, h, 1<<18, 8, 1, 64)
	if err != nil {
		panic(err)
	}
	runtime.GC()

	for i := 0; i < 32; i++ {
		dst[i] ^= k[i]
	}

	c1, _ := aes.NewCipher(k[32:48])
	c1.Encrypt(dst[0:16], dst[0:16])

	c2, _ := aes.NewCipher(k[48:64])
	c2.Encrypt(dst[16:32], dst[16:32])

	// add padding
	dst[36] = 0xff
	return dst
}
450233
func Encrypt(password string, plaintext []byte) (encrypted []byte, err error) {
	// Derive key material from password and salt.
	salt := make([]byte, 8)
	_, err = io.ReadFull(rand.Reader, salt)
	if err != nil {
		return nil, err
	}
	aesKey, hmacKey, keyHash := deriveKey(password, salt)

	// Pad.
	n := aes.BlockSize - len(plaintext)%aes.BlockSize
	dec := make([]byte, len(plaintext)+n)
	copy(dec, plaintext)
	for i := len(plaintext); i < len(dec); i++ {
		dec[i] = byte(n)
	}

	// Encrypt.
	iv := make([]byte, aes.BlockSize)
	_, err = io.ReadFull(rand.Reader, iv)
	if err != nil {
		return nil, err
	}
	aesBlock, err := aes.NewCipher(aesKey)
	if err != nil {
		// Cannot happen - key is right size.
		panic("aes: " + err.Error())
	}
	m := cipher.NewCBCEncrypter(aesBlock, iv)
	enc := make([]byte, len(dec))
	m.CryptBlocks(enc, dec)

	// Construct packet.
	var pkt []byte
	pkt = append(pkt, version)
	pkt = append(pkt, salt...)
	pkt = append(pkt, keyHash...)
	pkt = append(pkt, iv...)
	pkt = append(pkt, enc...)

	// Sign.
	h := hmac.New(sha1.New, hmacKey)
	h.Write(pkt)
	pkt = append(pkt, h.Sum(nil)...)

	return pkt, nil
}
891225
func (kw KeyWrapEncrypt) KeyDecrypt(enckey []byte) ([]byte, error) {
	block, err := aes.NewCipher(kw.sharedkey)
	if err != nil {
		return nil, errors.Wrap(err, "failed to create cipher from shared key")
	}

	cek, err := keyunwrap(block, enckey)
	if err != nil {
		return nil, errors.Wrap(err, "failed to unwrap data")
	}
	return cek, nil
}
492373
func (e *Envelope) Seal(options *MessageParams) error {
	if options.PoW == 0 {
		// PoW is not required
		return nil
	}

	var target, bestLeadingZeros int
	if options.PoW < 0 {
		// target is not set - the function should run for a period
		// of time specified in WorkTime param. Since we can predict
		// the execution time, we can also adjust Expiry.
		e.Expiry += options.WorkTime
	} else {
		target = e.powToFirstBit(options.PoW)
	}

	buf := make([]byte, 64)
	h := crypto.Keccak256(e.rlpWithoutNonce())
	copy(buf[:32], h)

	finish := time.Now().Add(time.Duration(options.WorkTime) * time.Second).UnixNano()
	for nonce := uint64(0); time.Now().UnixNano() < finish; {
		for i := 0; i < 1024; i++ {
			binary.BigEndian.PutUint64(buf[56:], nonce)
			d := new(big.Int).SetBytes(crypto.Keccak256(buf))
			leadingZeros := 256 - d.BitLen()
			if leadingZeros > bestLeadingZeros {
				e.Nonce, bestLeadingZeros = nonce, leadingZeros
				if target > 0 && bestLeadingZeros >= target {
					return nil
				}
			}
			nonce++
		}
	}

	if target > 0 && bestLeadingZeros < target {
		return fmt.Errorf("failed to reach the PoW target, specified pow time (%d seconds) was insufficient", options.WorkTime)
	}

	return nil
}
1213810
func (u *vault) Unseal() error {
	for i := 0; ; i++ {
		keyID := u.unsealKeyForID(i)

		logrus.Debugf("retrieving key from kms service...")
		k, err := u.keyStore.Get(keyID)

		if err != nil {
			return fmt.Errorf("unable to get key '%s': %s", keyID, err.Error())
		}

		logrus.Debugf("sending unseal request to vault...")
		resp, err := u.cl.Sys().Unseal(string(k))

		if err != nil {
			return fmt.Errorf("fail to send unseal request to vault: %s", err.Error())
		}

		logrus.Debugf("got unseal response: %+v", *resp)

		if !resp.Sealed {
			return nil
		}

		// if progress is 0, we failed to unseal vault.
		if resp.Progress == 0 {
			return fmt.Errorf("failed to unseal vault. progress reset to 0")
		}
	}
}
575647
func EncryptAndSeal(key, nonce, message []byte, add []byte) ([]byte /*encrypted*/, [16]byte /*mac*/, error) {
	var mac [poly1305.TagSize]byte
	if len(key) != 32 {
		return nil, mac, errors.New("invalid key size")
	}
	if len(nonce) != 8 {
		return nil, mac, errors.New("invalid nonce size")
	}

	var (
		Nonce   [12]byte
		aeadOut = make([]byte, len(message)+poly1305.TagSize)
	)
	copy(Nonce[4:], nonce)

	aead, err := chacha20poly1305.New(key)
	if err != nil {
		return nil, mac, err
	}

	aeadOut = aead.Seal(aeadOut[:0], Nonce[:], message, add)
	copy(mac[:], aeadOut[len(message):])
	return aeadOut[:len(message)], mac, nil
}
879338
func (b *Boxer) seal(data interface{}, key libkb.NaclSecretBoxKey) (*chat1.EncryptedData, error) {
	s, err := b.marshal(data)
	if err != nil {
		return nil, err
	}

	var nonce [libkb.NaclDHNonceSize]byte
	if _, err := rand.Read(nonce[:]); err != nil {
		return nil, err
	}

	var encKey [libkb.NaclSecretBoxKeySize]byte = key

	sealed := secretbox.Seal(nil, []byte(s), &nonce, &encKey)
	enc := &chat1.EncryptedData{
		V: 1,
		E: sealed,
		N: nonce[:],
	}

	return enc, nil
}
1260602
func Aes192CBCEncrypt(key [24]byte, plaintext []byte) (ciphertext []byte, err error) {
	return aesCBCEnc(key[:], plaintext)
}
1010736
func Seal(out, nonce, message, key []byte) []byte {
	if len(nonce) != NonceSize {
		panic("unsupported nonce size")
	}
	if len(key) != KeySize {
		panic("unsupported key size")
	}

	var firstBlock [64]byte
	cipher, _ := chacha.NewCipher(nonce, key, 20)
	cipher.XORKeyStream(firstBlock[:], firstBlock[:])
	var polyKey [32]byte
	copy(polyKey[:], firstBlock[:32])

	ret, out := sliceForAppend(out, TagSize+len(message))
	firstMessageBlock := message
	if len(firstMessageBlock) > 32 {
		firstMessageBlock = firstMessageBlock[:32]
	}

	tagOut := out
	out = out[poly1305.TagSize:]
	for i, x := range firstMessageBlock {
		out[i] = firstBlock[32+i] ^ x
	}
	message = message[len(firstMessageBlock):]
	ciphertext := out
	out = out[len(firstMessageBlock):]

	cipher.SetCounter(1)
	cipher.XORKeyStream(out, message)

	var tag [TagSize]byte
	hash := poly1305.New(polyKey)
	hash.Write(ciphertext)
	hash.Sum(tag[:0])
	copy(tagOut, tag[:])

	return ret
}
1153445
func (b *AESGCMBarrier) Encrypt(ctx context.Context, key string, plaintext []byte) ([]byte, error) {
	b.l.RLock()
	if b.sealed {
		b.l.RUnlock()
		return nil, ErrBarrierSealed
	}

	term := b.keyring.ActiveTerm()
	primary, err := b.aeadForTerm(term)
	b.l.RUnlock()
	if err != nil {
		return nil, err
	}

	ciphertext, err := b.encrypt(key, term, primary, plaintext)
	if err != nil {
		return nil, err
	}
	return ciphertext, nil
}