// Returns the amount of messages the specified symmetric key
// is still valid for under the handshake scheme
2917
func (api *HandshakeAPI) GetHandshakeKeyCapacity(symkeyid string) (uint16, error) {
	storekey := api.ctrl.getSymKey(symkeyid)
	if storekey == nil {
		return 0, fmt.Errorf("invalid symkey id %s", symkeyid)
	}
	return storekey.limit - storekey.count, nil
}
51223
func encryptedMessageFromBytes(data []byte) (EncryptedMessage, error) {

	var err error
	var lengthData [8]byte
	var nonceData [nonceSize]byte
	minimumDataSize := 8 + nonceSize
	m := EncryptedMessage{}

	// check if the data is smaller than 36 which is the minimum
	if data == nil {
		return m, MessageParsingError
	}

	if len(data) < minimumDataSize+1 {
		return m, MessageParsingError
	}

	lenght := data[:8]
	nonce := data[8 : 8+nonceSize] // 24 bytes
	message := data[minimumDataSize:]

	total := copy(lengthData[:], lenght)
	if total != 8 {
		return m, MessageParsingError
	}

	total = copy(nonceData[:], nonce)
	if total != nonceSize {
		return m, MessageParsingError
	}

	m.length = smallendian.FromUint64(lengthData)
	m.nonce = nonceData
	m.data = message
	return m, err

}
1298647
func (h *cryptoSetup) ReadHandshakeMessage() ([]byte, error) {
	msg, ok := <-h.messageChan
	if !ok {
		return nil, errors.New("error while handling the handshake message")
	}
	return msg, nil
}
1181342
func (cipher CipherFunction) KeySize() int {
	switch cipher {
	case Cipher3DES:
		return 24
	case CipherCAST5:
		return cast5.KeySize
	case CipherAES128:
		return 16
	case CipherAES192:
		return 24
	case CipherAES256:
		return 32
	}
	return 0
}
1246657
func decryptMessage(key, msg []byte, data []byte) ([]byte, error) {
	// 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
	}

	// Success!
	return plain, nil
}
415492
func CountSigOps(tx *btcutil.Tx) int {
	msgTx := tx.MsgTx()

	// Accumulate the number of signature operations in all transaction
	// inputs.
	totalSigOps := 0
	for _, txIn := range msgTx.TxIn {
		numSigOps := txscript.GetSigOpCount(txIn.SignatureScript)
		totalSigOps += numSigOps
	}

	// Accumulate the number of signature operations in all transaction
	// outputs.
	for _, txOut := range msgTx.TxOut {
		numSigOps := txscript.GetSigOpCount(txOut.PkScript)
		totalSigOps += numSigOps
	}

	return totalSigOps
}
916679
func (ctl *HandshakeController) cleanHandshake(pubkeyid string, topic *Topic, in bool, out bool) int {
	ctl.lock.Lock()
	defer ctl.lock.Unlock()
	var deletecount int
	var deletes []string
	now := time.Now()
	handshake := ctl.handshakes[pubkeyid][*topic]
	log.Debug("handshake clean", "pubkey", pubkeyid, "topic", topic)
	if in {
		for i, key := range handshake.inKeys {
			if key.expiredAt.Before(now) || (key.expiredAt.IsZero() && key.limit <= key.count) {
				log.Trace("handshake in clean remove", "symkeyid", *key.symKeyID)
				deletes = append(deletes, *key.symKeyID)
				handshake.inKeys[deletecount] = handshake.inKeys[i]
				deletecount++
			}
		}
		handshake.inKeys = handshake.inKeys[:len(handshake.inKeys)-deletecount]
	}
	if out {
		deletecount = 0
		for i, key := range handshake.outKeys {
			if key.expiredAt.Before(now) && (key.expiredAt.IsZero() && key.limit <= key.count) {
				log.Trace("handshake out clean remove", "symkeyid", *key.symKeyID)
				deletes = append(deletes, *key.symKeyID)
				handshake.outKeys[deletecount] = handshake.outKeys[i]
				deletecount++
			}
		}
		handshake.outKeys = handshake.outKeys[:len(handshake.outKeys)-deletecount]
	}
	for _, keyid := range deletes {
		delete(ctl.symKeyIndex, keyid)
		ctl.pss.symKeyPool[keyid][*topic].protected = false
	}
	return len(deletes)
}
279928
func (wsh *WebsocketHub) NumClients() int {
	// Swallow any type assertion error since the default int of 0 is OK.
	n, _ := wsh.numClients.Load().(int)
	return n
}
722491
func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) error {
	if !ske.Encrypted {
		return nil
	}

	key := make([]byte, ske.CipherFunc.KeySize())
	ske.s2k(key, passphrase)

	if len(ske.encryptedKey) == 0 {
		ske.Key = key
	} else {
		// the IV is all zeros
		iv := make([]byte, ske.CipherFunc.blockSize())
		c := cipher.NewCFBDecrypter(ske.CipherFunc.new(key), iv)
		c.XORKeyStream(ske.encryptedKey, ske.encryptedKey)
		ske.CipherFunc = CipherFunction(ske.encryptedKey[0])
		if ske.CipherFunc.blockSize() == 0 {
			return errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(ske.CipherFunc)))
		}
		ske.CipherFunc = CipherFunction(ske.encryptedKey[0])
		ske.Key = ske.encryptedKey[1:]
		if len(ske.Key)%ske.CipherFunc.blockSize() != 0 {
			ske.Key = nil
			return errors.StructuralError("length of decrypted key not a multiple of block size")
		}
	}

	ske.Encrypted = false
	return nil
}
368825
func (d *indirectIndex) KeyCount() int {
	d.mu.RLock()
	n := len(d.ro.offsets)
	d.mu.RUnlock()
	return n
}
195690
func calcMac(key [keyLen]byte, msg []byte) [HMACSize]byte {
	hmac := hmac.New(sha256.New, key[:])
	hmac.Write(msg)
	h := hmac.Sum(nil)

	var mac [HMACSize]byte
	copy(mac[:], h[:HMACSize])

	return mac
}
807039
func KeyLength(key interface{}) int {
	if key == nil {
		return 0
	}
	if ecdsaKey, ok := key.(*ecdsa.PublicKey); ok {
		return ecdsaKey.Curve.Params().BitSize
	} else if rsaKey, ok := key.(*rsa.PublicKey); ok {
		return rsaKey.N.BitLen()
	}

	return 0
}
1210224
func (ks *KeyStore) GetSymmetricKey(symkeyid string) ([]byte, error) {
	return ks.w.GetSymKey(symkeyid)
}
606304
func (api *HandshakeAPI) SendSym(symkeyid string, topic Topic, msg hexutil.Bytes) (err error) {
	err = api.ctrl.pss.SendSym(symkeyid, topic, msg[:])
	if otherErr := api.ctrl.registerSymKeyUse(symkeyid); otherErr != nil {
		return otherErr
	}
	return err
}
769134
func (msg *ReceivedMessage) decryptAsymmetric(key *ecdsa.PrivateKey) error {
	decrypted, err := ecies.ImportECDSA(key).Decrypt(msg.Raw, nil, nil)
	if err == nil {
		msg.Raw = decrypted
	}
	return err
}
312931
func messageSizeToBitLength(messageSize int) int {
	bytes := float64(messageSize)
	header := math.Ceil(math.Floor(math.Log2(bytes)+1) / 8.0)
	return int(header)
}
21934
func DecryptAndVerify(key, nonce, message []byte, mac [16]byte, add []byte) ([]byte, error) {
	if len(key) != 32 {
		return nil, errors.New("invalid key size")
	}
	if len(nonce) != 8 {
		return nil, errors.New("invalid nonce size")
	}

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

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

	return aead.Open(aeadOut[:0], Nonce[:], append(message, mac[:]...), add)
}