Exemplo n.º 1
0
func decryptMessageInner(sealed []byte, nonce *[24]byte, from *Contact) ([]byte, bool) {
	if plaintext, ok := box.Open(nil, sealed, nonce, &from.theirLastDHPublic, &from.lastDHPrivate); ok {
		return plaintext, true
	}

	if plaintext, ok := box.Open(nil, sealed, nonce, &from.theirCurrentDHPublic, &from.lastDHPrivate); ok {
		return plaintext, true
	}

	plaintext, ok := box.Open(nil, sealed, nonce, &from.theirLastDHPublic, &from.currentDHPrivate)
	if !ok {
		plaintext, ok = box.Open(nil, sealed, nonce, &from.theirCurrentDHPublic, &from.currentDHPrivate)
		if !ok {
			return nil, false
		}
	}

	// They have clearly received our current DH value. Time to
	// rotate.
	copy(from.lastDHPrivate[:], from.currentDHPrivate[:])
	if _, err := io.ReadFull(rand.Reader, from.currentDHPrivate[:]); err != nil {
		panic(err)
	}
	return plaintext, true
}
Exemplo n.º 2
0
func decryptMessage(sealed []byte, from *Contact) ([]byte, error) {
	if from.ratchet != nil {
		plaintext, err := from.ratchet.Decrypt(sealed)
		if err != nil {
			return nil, err
		}
		return plaintext, nil
	}

	var nonce [24]byte
	if len(sealed) < len(nonce) {
		return nil, errors.New("message shorter than nonce")
	}
	copy(nonce[:], sealed)
	sealed = sealed[24:]
	headerLen := ephemeralBlockLen - len(nonce)
	if len(sealed) < headerLen {
		return nil, errors.New("message shorter than header")
	}

	publicBytes, ok := decryptMessageInner(sealed[:headerLen], &nonce, from)
	if !ok || len(publicBytes) != 32 {
		return nil, errors.New("failed to decrypt inner message")
	}
	var innerNonce [nonceLen]byte
	sealed = sealed[headerLen:]
	copy(innerNonce[:], sealed)
	sealed = sealed[nonceLen:]
	var ephemeralPublicKey [32]byte
	copy(ephemeralPublicKey[:], publicBytes)

	if plaintext, ok := box.Open(nil, sealed, &innerNonce, &ephemeralPublicKey, &from.lastDHPrivate); ok {
		return plaintext, nil
	}

	plaintext, ok := box.Open(nil, sealed, &innerNonce, &ephemeralPublicKey, &from.currentDHPrivate)
	if !ok {
		return nil, errors.New("failed to decrypt with either DH values (old ratchet)")
	}

	// They have clearly received our current DH value. Time to
	// rotate.
	copy(from.lastDHPrivate[:], from.currentDHPrivate[:])
	if _, err := io.ReadFull(rand.Reader, from.currentDHPrivate[:]); err != nil {
		panic(err)
	}
	return plaintext, nil
}
Exemplo n.º 3
0
// Reads an encrypted message from the reader expecting the following structure:
// The first two bytes are the length(x) of the encrypted message.
// The next 24 bytes are the nonce.
// The next x bytes is the encrypted message.
func (s *SecureReader) Read(p []byte) (int, error) {
	er := &errReader{r: s.reader}

	plen := make([]byte, 2)
	er.read(plen)

	payloadLen, err := binary.ReadVarint(bytes.NewBuffer(plen))
	if err != nil {
		return 0, errors.New("Invalid length bytes")
	}

	nonce := make([]byte, 24)
	er.read(nonce)

	payload := make([]byte, payloadLen)
	er.read(payload)

	if er.err != nil {
		return 0, er.err
	}

	nonceArray := &[24]byte{}
	copy(nonceArray[:], nonce)

	message, success := box.Open(nil, payload, nonceArray, s.pub, s.priv)
	if !success {
		return 0, errors.New("Decrypt failure")
	}

	copy(p, message)
	return len(message), nil
}
Exemplo n.º 4
0
// Read decrypts a stream encrypted with box.Seal.
// It expects the nonce used to be prepended
// to the ciphertext
func (s Reader) Read(p []byte) (int, error) {
	// make a buffer large enough to handle
	// the overhead associated with an encrypted message
	// (the tag and nonce)
	enc := make([]byte, (len(p) + TotalOverhead))
	n, err := s.r.Read(enc)

	if err != nil {
		return n, err
	}

	// strip off the nonce
	// and any extra space at the end of the buffer
	nonceSlice := enc[:NonceSize]
	enc = enc[NonceSize:n]

	// convert the slice to an array
	// for use in box.Open
	var nonce [NonceSize]byte
	copy(nonce[:], nonceSlice)

	decrypt, auth := box.Open(nil, enc, &nonce, s.pub, s.priv)
	// if authentication failed, output bottom
	if !auth {
		return 0, ErrDecrypt
	}

	if len(decrypt) > len(p) {
		return 0, ErrDecrypt
	}

	n = copy(p, decrypt)

	return n, nil
}
Exemplo n.º 5
0
func boxOpen(encryptedData []byte, nonce [24]byte, peersPublicKey NaclDHKeyPublic, privateKey *NaclDHKeyPrivate) ([]byte, error) {
	data, ok := box.Open(nil, encryptedData, &nonce, (*[32]byte)(&peersPublicKey), (*[32]byte)(privateKey))
	if ok {
		return data, nil
	}
	return data, DecryptionError{}
}
Exemplo n.º 6
0
Arquivo: crypto.go Projeto: 40a/ejson
func (d *Decrypter) decrypt(bm *boxedMessage) ([]byte, error) {
	plaintext, ok := box.Open(nil, bm.Box, &bm.Nonce, &bm.EncrypterPublic, &d.Keypair.Private)
	if !ok {
		return nil, ErrDecryptionFailed
	}
	return plaintext, nil
}
Exemplo n.º 7
0
func (c *Conversation) Open(ctxt []byte, round uint32, role byte) ([]byte, bool) {
	var nonce [24]byte
	binary.BigEndian.PutUint32(nonce[:], round)
	nonce[23] = role

	return box.Open(nil, ctxt, &nonce, c.peerPublicKey.Key(), c.myPrivateKey.Key())
}
Exemplo n.º 8
0
// Read decrypts a message from the underlying data stream, and stores
// the contents into out, returning the number of bytes read, and any
// error occurred while reading the data. The encrypted data contains
// the nonce (24 bytes), box size (2 bytes), and box (remaining bytes).
func (r *SecureReader) Read(out []byte) (n int, err error) {
	// "Sticky error" read function.
	read := func(buf []byte) {
		if err != nil {
			return
		}
		_, err = io.ReadFull(r.r, buf)
	}

	var (
		nonce [24]byte
		size  = make([]byte, 2)
	)

	read(nonce[:])
	read(size)
	boxed := make([]byte, binary.LittleEndian.Uint16(size)) // Allocate the box bytes.
	read(boxed)

	if err != nil {
		return
	}

	message, ok := box.Open(out[:0], boxed, &nonce, r.ppub, r.priv)
	if !ok {
		err = errors.New("cannot open box")
	}
	n = len(message)
	return
}
Exemplo n.º 9
0
func (h *decodeHeader) decode() (data []byte, version int, err error) {
	if !h.gotRecipient {
		err = errors.New("Cannot decode header until recipient defined")
		panic(err)
	}
	// Length to decode should be lenEndBytes plus the NaCl Box overhead
	var senderPK [32]byte
	copy(senderPK[:], h.header[16:48])
	var nonce [24]byte
	copy(nonce[:], h.header[48:72])
	data, auth := box.Open(
		nil,
		h.header[72:248],
		&nonce,
		&senderPK,
		&h.recipientSK,
	)
	if !auth {
		err = errors.New("Authentication failed decrypting slot data")
		return
	}
	// Version number is the first byte of decrypted data
	version = int(data[0])
	return
}
Exemplo n.º 10
0
// Read reads a complete length-prefixed message from sr.from and
// decrypts it into p. It returns the number of bytes read from thea
// reader.
//
// If the message has a wrong signature, it returns
// an ErrBadMessage.
func (sr secureReader) Read(p []byte) (n int, err error) {
	var l uint16
	err = binary.Read(sr.from, binary.BigEndian, &l)
	if err != nil {
		return 0, err
	}

	content := make([]byte, l)
	nn, err := sr.from.Read(content)
	if err != nil {
		return 0, err
	}
	if nn != len(content) {
		return 0, ErrShortSecureRead
	}

	// Make sure p is big enough
	if len(p) < int(l)-24-box.Overhead {
		return 0, ErrShortSecureRead
	}

	var nonce [24]byte
	copy(nonce[:], content[:])

	_, ok := box.Open(p[:0], content[len(nonce):], &nonce, sr.pub, sr.priv)
	if !ok {
		err = ErrBadMessage
	}

	return int(l) - len(nonce) - box.Overhead, err
}
Exemplo n.º 11
0
// Read a decrypted message into p.
//
// The SecureReader reads the contents written by a SecureWriter.
// It will attempt to read/parse according to the following format:
//
// - Nonce: nonceSize bytes (in this case, 24)
// - Message Length (uint32): length of the encrypted message, in bytes.
// - Encrypted Message: the encrypted message itself.
//
// It decrypts the message using the nonce and the values of the
// SecureReader's public and private keys and copies the decrypted
// message into the first n bytes of p.
//
// Returns the length (in bytes) of the decrypted message.
func (r SecureReader) Read(p []byte) (n int, err error) {
	// read the nonce
	var nonce [nonceSize]byte
	err = binary.Read(r.reader, binary.LittleEndian, &nonce)
	if err != nil && err != io.EOF {
		return 0, errors.New("could not read nonce: " + err.Error())
	}

	// read the length of the encrypted message
	var msgLen uint32
	err = binary.Read(r.reader, binary.LittleEndian, &msgLen)
	if err != nil && err != io.EOF {
		return 0, errors.New("could not read message length: " + err.Error())
	}

	// read the encrypted message itself
	encrypted := make([]byte, msgLen)
	err = binary.Read(r.reader, binary.LittleEndian, &encrypted)
	if err != nil && err != io.EOF {
		return 0, errors.New("could not read encrypted message: " + err.Error())
	}

	// decrypt the message
	decrypted, res := box.Open(nil, encrypted, &nonce, r.publicKey, r.privateKey)
	if res == false {
		return 0, errors.New("error decrypting mesage with box.Open")
	}

	copy(p, decrypted)

	return int(msgLen) - secretbox.Overhead, nil
}
Exemplo n.º 12
0
func (t KeyPairType) Open(message, nonce, peersPublicKey, privateKey []byte) ([]byte, error) {
	if err := t.checkNonceAndKeys(nonce, peersPublicKey, privateKey); err != nil {
		return nil, err
	}

	switch t {
	case Curve25519:
		var (
			ok              bool
			pubKey, privKey [32]byte
			n               [24]byte
		)
		copy(n[:], nonce)
		copy(pubKey[:], peersPublicKey)
		copy(privKey[:], privateKey)
		out := make([]byte, 0, len(message)-box.Overhead)
		out, ok = box.Open(out, message, &n, &pubKey, &privKey)
		if !ok {
			return nil, ErrMessageIntegrityFailed
		}
		return out, nil
	default:
		return nil, ErrInvalidKey
	}
}
Exemplo n.º 13
0
// Perform a secure read
func (s SecureReadWriteCloser) Read(p []byte) (int, error) {
	var err error
	if s.reader == nil {
		panic("reader is nil")
	}

	nonce := [NonceLength]byte{}
	in := make([]byte, 32768)

	// The nonce should be the first thing to read
	_, err = io.ReadFull(s.reader, nonce[:])
	if err != nil {
		log.Println("Error reading nonce", err)
		return 0, err
	}

	x, err := s.reader.Read(in)
	if err != nil {
		log.Println("Error reading encrypted payload", err)
		return 0, err
	}
	in = in[:x]

	tmp := []byte{}
	// Documentation for box.Open really needs some attention. The return value isn't
	// even mentioned.
	out, ok := box.Open(tmp, in, &nonce, s.pub, s.priv)
	if !ok {
		log.Println("box.Open failed")
		return 0, errors.New("box.Open failed")
	}
	z := copy(p, out)
	return z, nil
}
Exemplo n.º 14
0
// Blocking read until the whole encrypted message is received
// Encrypted messages are in the format:
//   message = | 4-byte little-endian uint32 for payload size | payload |
//   payload = | 24-byte nonce | encrypted message |
func (sr *SecureReader) ReadNextEncryptedMessage() error {
	// Read the payload size out of the buffer
	var payloadSize uint32
	err := binary.Read(sr.r, binary.LittleEndian, &payloadSize)
	if err != nil {
		if err != io.EOF {
			log.Println("Error reading payloadSize from buffer", err)
		}
		return err
	}

	// Read the payload
	data := make([]byte, payloadSize)
	_, err = io.ReadFull(sr.r, data)
	if err != nil {
		log.Println("Error reading payload from buffer", err)
		return err
	}

	// Unpack the nonce and encrypted message
	nonce := data[0:24]
	encrypted := data[24:]

	// Decrypt the encrypted message
	var nonceBuf [24]byte
	copy(nonceBuf[:], nonce)
	decrypted, success := box.Open(make([]byte, 0), encrypted, &nonceBuf, sr.pub, sr.priv)
	if success {
		sr.leftover = decrypted
		return nil
	} else {
		log.Println("Error decrypting message")
		return &ReadError{"Error decrypting message"}
	}
}
Exemplo n.º 15
0
// Unbox runs the NaCl unbox operation on the given ciphertext and nonce,
// using the receiver as the secret key.
func (k SecretKey) Unbox(sender saltpack.BoxPublicKey, nonce *saltpack.Nonce, msg []byte) ([]byte, error) {
	ret, ok := box.Open([]byte{}, msg, (*[24]byte)(nonce), (*[32]byte)(sender.ToRawBoxKeyPointer()), (*[32]byte)(&k.sec))
	if !ok {
		return nil, saltpack.ErrDecryptionFailed
	}
	return ret, nil
}
Exemplo n.º 16
0
// decodeCaveatIdV0 decodes a version 0 caveat id.
func decodeCaveatIdV0(key *KeyPair, id []byte) (caveatInfo, error) {
	if len(id) < 1+publicKeyPrefixLen+KeyLen+NonceLen+box.Overhead {
		return caveatInfo{}, errgo.New("caveat id too short")
	}
	id = id[1:] // skip version (already checked)

	publicKeyPrefix, id := id[:publicKeyPrefixLen], id[publicKeyPrefixLen:]
	if !bytes.Equal(key.Public.Key[:publicKeyPrefixLen], publicKeyPrefix) {
		return caveatInfo{}, errgo.New("public key mismatch")
	}

	var peerPublicKey PublicKey
	copy(peerPublicKey.Key[:], id[:KeyLen])
	id = id[KeyLen:]

	var nonce [NonceLen]byte
	copy(nonce[:], id[:NonceLen])
	id = id[NonceLen:]

	data, ok := box.Open(nil, id, &nonce, peerPublicKey.boxKey(), key.Private.boxKey())
	if !ok {
		return caveatInfo{}, errgo.Newf("cannot decrypt caveat id")
	}
	ci, err := decodeSecretPartV0(data)
	if err != nil {
		return caveatInfo{}, errgo.Notef(err, "invalid secret part")
	}
	ci.peerPublicKey = &peerPublicKey
	return ci, nil
}
Exemplo n.º 17
0
// Read will read ciphertext from reader, and put plaintext into slice p.
// See Write documentation for details on the data format.
func (r SecureReader) Read(p []byte) (int, error) {
	// Read the plaintext nonce from the stream
	var nonce [24]byte
	err := binary.Read(r.reader, binary.BigEndian, &nonce)
	if err != nil {
		return 0, err
	}

	// Read message length from the stream.
	// Since the longest expected message is 32KB, only two bytes are necessary.
	var length uint16
	err = binary.Read(r.reader, binary.BigEndian, &length)
	if err != nil {
		return 0, err
	}

	// Read the ciphertext from the stream.
	// The ciphertext will be the message length, plus the amount of overhead.
	ct := make([]byte, length+box.Overhead)
	err = binary.Read(r.reader, binary.BigEndian, &ct)
	if err != nil {
		return 0, err
	}

	// Decrypt the message.
	opened, ok := box.Open(nil, ct, &nonce, r.publicKey, r.privateKey)
	if !ok {
		return 0, ErrWhileDecrypting
	}

	copy(p, opened)

	return len(opened), nil
}
Exemplo n.º 18
0
// UnboxBytes32 decrypts the given message with the current user's
// private encryption key and the given nonce and peer public key.
func UnboxBytes32(g *libkb.GlobalContext, secretUI libkb.SecretUI,
	arg keybase1.UnboxBytes32Arg) (bytes32 keybase1.Bytes32, err error) {
	encryptionKey, err := getMySecretKey(
		g, secretUI, libkb.DeviceEncryptionKeyType, arg.Reason)
	if err != nil {
		return
	}

	kp, ok := encryptionKey.(libkb.NaclDHKeyPair)
	if !ok || kp.Private == nil {
		err = libkb.KeyCannotDecryptError{}
		return
	}

	decryptedData, ok := box.Open(nil, arg.EncryptedBytes32[:],
		(*[24]byte)(&arg.Nonce), (*[32]byte)(&arg.PeersPublicKey),
		(*[32]byte)(kp.Private))
	if !ok {
		err = libkb.DecryptionError{}
		return
	}

	if len(decryptedData) != len(bytes32) {
		err = libkb.DecryptionError{}
		return
	}

	copy(bytes32[:], decryptedData)
	return
}
Exemplo n.º 19
0
func (r *secureReader) Read(p []byte) (int, error) {

	// Read the nonce -- 24 bytes.
	var nonce [24]byte
	if _, err := io.ReadFull(r.reader, nonce[:]); err != nil {
		return 0, err
	}

	// Read the message size -- 2 bytes.
	var size uint16
	if err := binary.Read(r.reader, binary.LittleEndian, &size); err != nil {
		return 0, err
	}

	// Read in the message body -- variable bytes.
	body := make([]byte, size)
	if _, err := io.ReadFull(r.reader, body); err != nil {
		return 0, err
	}

	// Decrypt the message body.
	var decrypted []byte
	decrypted, ok := box.Open(nil, body, &nonce, r.pub, r.priv)
	if !ok {
		return 0, errors.New("could not open box")
	}
	n := copy(p, decrypted)
	return n, nil
}
Exemplo n.º 20
0
func (d *Dialer) HandleDialBucket(db *DialBucket) {
	nonce := ForwardNonce(db.Round)

OUTER:
	for _, b := range db.Intros {
		var pk [32]byte
		copy(pk[:], b[0:32])
		data, ok := box.Open(nil, b[32:], nonce, &pk, d.myPrivateKey.Key())
		if !ok {
			continue
		}

		intro := new(Introduction)
		if err := intro.Unmarshal(data); err != nil {
			continue
		}

		for name, key := range d.pki.People {
			if *key == intro.LongTermKey {
				d.gui.Warnf("Received introduction: %s\n", name)
				continue OUTER
			}
		}
		d.gui.Warnf("Received introduction: (%s)\n", &intro.LongTermKey)
	}
}
Exemplo n.º 21
0
// NewSecureReader instantiates a new SecureReader
func NewSecureReader(r io.Reader, priv, pub *[32]byte) io.Reader {
	return readerFunc(func(p []byte) (int, error) {
		var size int32
		//first read size of payload
		binary.Read(r, binary.BigEndian, &size)
		if int32(len(p)) < size {
			return 0, fmt.Errorf("Supplied buffer of size %d not large enough for message of size %d.", len(p), size)
		}
		//make buffer big enough for nonce + payload + overhead
		buf := make([]byte, size+24+box.Overhead)
		n, err := io.ReadFull(r, buf)
		if err != nil {
			return n, err
		}
		nonce := [24]byte{}
		copy(nonce[:], buf[:24])
		msg := buf[24:n]
		output, ok := box.Open(nil, msg, &nonce, pub, priv)
		if !ok {
			return 0, fmt.Errorf("Error decrypting message")
		}
		n = copy(p, output)
		return n, err
	})
}
Exemplo n.º 22
0
// Read reads encrypted message from input stream r.
func (sr *SecureReader) Read(p []byte) (n int, err error) {
	var (
		h  header // Header (nonce + message length)
		d  []byte // Decrypted message
		ok bool
	)

	// Read header.
	if err = binary.Read(sr.r, binary.BigEndian, &h); err != nil {
		return
	}

	// Read encrypted message.
	encrypted := make([]byte, h.MessageLen)
	if _, err = sr.r.Read(encrypted); err != nil {
		return
	}

	// Decrypts encrypted message.
	if d, ok = box.Open(d, encrypted, &h.Nonce, sr.pub, sr.priv); !ok {
		return n, errors.New("Unable to decrypt encrypted message")
	}
	n = copy(p, d)

	return
}
Exemplo n.º 23
0
func (sr *SecureReader) Read(p []byte) (n int, err error) {
	var (
		nonce  [24]byte
		length int64
	)

	if err := binary.Read(sr.R, binary.LittleEndian, nonce[:]); err != nil {
		return 0, err
	}

	if err := binary.Read(sr.R, binary.LittleEndian, &length); err != nil {
		return 0, err
	}

	lr := io.LimitReader(sr.R, length)
	b, err := ioutil.ReadAll(lr)

	if err != nil {
		return 0, err
	}

	buf, ok := box.Open(nil, b, &nonce, sr.Pub, sr.Prv)

	if !ok {
		return 0, errors.New("decryption failed")
	}

	if sr.br == nil || sr.br.Len() == 0 {
		sr.br = bytes.NewReader(buf)
	}

	return sr.br.Read(p)
}
Exemplo n.º 24
0
func (id *Identity) DecryptPacket(encrypted *EncryptedPacket) (*PlainPacket, error) {
	plain := PlainPacket{
		Sender: encrypted.Sender,
	}
	switch encrypted.Kind {
	case netPacketPing:
		plain.Payload = &PingPong{}
	case netPacketPong:
		plain.Payload = &PingPong{}
	case netPacketGetNodes:
		plain.Payload = &GetNodes{}
	case netPacketGetNodesReply:
		plain.Payload = &GetNodesReply{}
	default:
		return nil, fmt.Errorf("Unknown packet type %d.", encrypted.Kind)
	}

	plainPayload, success := box.Open(nil, encrypted.Payload, encrypted.Nonce, encrypted.Sender, &id.PrivateKey)
	if !success {
		return nil, fmt.Errorf("Failed to decrypt.")
	}

	// decrypt payload
	err := plain.Payload.UnmarshalBinary(plainPayload)
	if err != nil {
		return nil, err
	}

	return &plain, nil
}
Exemplo n.º 25
0
func (h *Handler) auth(r *http.Request, client string) (*authRequest, error) {
	var msg wire.Message
	dec := json.NewDecoder(r.Body)
	err := dec.Decode(&msg)
	if err != nil {
		return nil, errgo.Mask(err)
	}

	clientKey, err := sf.DecodePublicKey(client)
	if err != nil {
		return nil, errgo.Mask(err)
	}

	nonce, err := sf.DecodeNonce(msg.ID)
	if err != nil {
		return nil, errgo.Mask(err)
	}

	out, ok := box.Open(nil, msg.Contents, (*[24]byte)(nonce), (*[32]byte)(clientKey), (*[32]byte)(h.keyPair.PrivateKey))
	if !ok {
		return nil, errgo.New("authentication failed")
	}

	return &authRequest{
		Handler:   h,
		ClientKey: clientKey,
		Nonce:     nonce,
		Contents:  out,
	}, nil
}
Exemplo n.º 26
0
func (srv *DialService) Add(args *DialAddArgs, _ *struct{}) error {
	log.WithFields(log.Fields{"service": "dial", "rpc": "Add", "round": args.Round, "onions": len(args.Onions)}).Debug()

	round, err := srv.getRound(args.Round, dialRoundOpen)
	if err != nil {
		return err
	}

	nonce := ForwardNonce(args.Round)
	messages := make([][]byte, 0, len(args.Onions))
	expectedOnionSize := srv.PKI.IncomingOnionOverhead(srv.ServerName) + SizeDialExchange

	for _, onion := range args.Onions {
		if len(onion) == expectedOnionSize {
			var theirPublic [32]byte
			copy(theirPublic[:], onion[0:32])

			message, ok := box.Open(nil, onion[32:], nonce, &theirPublic, srv.PrivateKey.Key())
			if ok {
				messages = append(messages, message)
			}
		}
	}

	round.Lock()
	round.incoming = append(round.incoming, messages...)
	round.Unlock()

	return nil
}
Exemplo n.º 27
0
func (r SecureReader) Read(p []byte) (int, error) {

	b := new([24]byte)

	err := binary.Read(r.reader, binary.LittleEndian, b)
	if err != nil {
		return 0, fmt.Errorf("Reading failed: %s", err)
	}

	buf := make([]byte, 1024)

	rb, err := r.reader.Read(buf)

	buf = buf[:rb]

	res, valid := box.Open(nil, buf, b, r.pubKey, r.privKey)

	if !valid {
		return 0, errors.New("Could not decrypt received message")
	}

	d := copy(p, res)

	return d, nil

}
Exemplo n.º 28
0
func unboxBytes32(encryptionKey libkb.GenericKey, ciphertext keybase1.EncryptedBytes32, nonce keybase1.BoxNonce, peerPubKey keybase1.BoxPublicKey) (bytes32 keybase1.Bytes32, err error) {
	kp, ok := encryptionKey.(libkb.NaclDHKeyPair)
	if !ok {
		err = libkb.KeyCannotDecryptError{}
		return
	}
	if kp.Private == nil {
		err = libkb.NoSecretKeyError{}
		return
	}

	decryptedData, ok := box.Open(nil, ciphertext[:], (*[24]byte)(&nonce), (*[32]byte)(&peerPubKey), (*[32]byte)(kp.Private))
	if !ok {
		err = libkb.DecryptionError{}
		return
	}

	if len(decryptedData) != len(bytes32) {
		err = libkb.DecryptionError{}
		return
	}

	copy(bytes32[:], decryptedData)
	return

}
Exemplo n.º 29
0
// Decrypt decrypts encrypted message em and return decrypted message m if and only if err == nil.
// If Box perform decryption using invalid key, it returns an error.
func (b Box) Decrypt(em []byte) (m []byte, err error) {
	var nonce [24]byte
	copy(nonce[:], em)
	if dm, ok := box.Open(nil, em[24:], &nonce, b.PeersPublicKey, b.privateKey); ok {
		return dm, nil
	}
	return nil, errDecryptMsg
}
Exemplo n.º 30
0
func (b boxSecretKey) Unbox(sender BoxPublicKey, nonce *Nonce, msg []byte) ([]byte, error) {
	out, ok := box.Open([]byte{}, msg, (*[24]byte)(nonce),
		(*[32]byte)(sender.ToRawBoxKeyPointer()), (*[32]byte)(&b.key))
	if !ok {
		return nil, errPublicKeyDecryptionFailed
	}
	return out, nil
}