Пример #1
0
// Source wraps the given DataSource, decrypting any secret values
func (s *SecretKey) Source(ds DataSource) DataSource {
	// If guestinfoSecretKey has a value, it should be our secret key.
	if val, _ := ds(guestinfoSecretKey); val != "" {
		if err := s.FromString(val); err != nil {
			log.Errorf("failed to decode %s: %s", guestinfoSecretKey, err)
		} else {
			log.Debugf("secret key decoded from %s", guestinfoSecretKey)
		}
	}

	return func(key string) (string, error) {
		val, err := ds(key)

		if err == nil && isSecret(key) {
			b, err := base64.StdEncoding.DecodeString(val)
			if err != nil {
				return "", err
			}

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

			plaintext, ok := secretbox.Open([]byte{}, b[24:], &nonce, &s.key)
			if !ok {
				return "", fmt.Errorf("failed to decrypt value for %s", key)
			}

			val = string(plaintext)
		}

		return val, err
	}
}
Пример #2
0
func (c *Crypt) Decrypt(keyArn string, data []byte) ([]byte, error) {
	var e *Envelope
	err := json.Unmarshal(data, &e)

	if err != nil {
		return nil, err
	}

	req := &kms.DecryptInput{
		CiphertextBlob: e.EncryptedKey,
	}

	res, err := KMS(c).Decrypt(req)

	if err != nil {
		return nil, err
	}

	var key [KeyLength]byte
	copy(key[:], res.Plaintext[0:KeyLength])

	var nonce [NonceLength]byte
	copy(nonce[:], e.Nonce[0:NonceLength])

	var dec []byte
	dec, ok := secretbox.Open(dec, e.Ciphertext, &nonce, &key)

	if !ok {
		return nil, fmt.Errorf("failed decryption")
	}

	return dec, nil
}
Пример #3
0
func (ds *decryptStream) processEncryptionBlock(bl *EncryptionBlock) ([]byte, error) {
	if err := bl.validate(); err != nil {
		return nil, err
	}

	if bl.seqno <= 0 {
		return nil, errPacketUnderflow
	}

	blockNum := encryptionBlockNumber(bl.seqno - 1)

	if err := blockNum.check(); err != nil {
		return nil, err
	}

	nonce := blockNum.newCounterNonce()

	sum := hashNonceAndAuthTag(nonce, bl.Ciphertext)
	if err := ds.checkMAC(bl, sum[:]); err != nil {
		return nil, err
	}

	plaintext, ok := secretbox.Open([]byte{}, bl.Ciphertext, (*[24]byte)(nonce), (*[32]byte)(&ds.sessionKey))
	if !ok {
		return nil, ErrBadCiphertext(bl.seqno)
	}

	// The encoding of the empty buffer implies the EOF.  But otherwise, all mechanisms are the same.
	if len(plaintext) == 0 {
		return nil, nil
	}
	return plaintext, nil
}
Пример #4
0
func (cah *connectionAwaitHandshake) readAndDecryptOne() (*capn.Segment, error) {
	if cah.sessionKey == nil {
		return capn.ReadFromStream(cah.socket, nil)
	}
	read, err := cah.socket.Read(cah.inBuff)
	if err != nil {
		return nil, err
	} else if read < len(cah.inBuff) {
		return nil, fmt.Errorf("Only read %v bytes, wanted %v", read, len(cah.inBuff))
	}
	copy(cah.nonceAryIn[16:], cah.inBuff[:8])
	msgLen := binary.BigEndian.Uint64(cah.inBuff[8:16])
	plainLen := msgLen - secretbox.Overhead
	msgBuf := make([]byte, plainLen+msgLen)
	for recvBuf := msgBuf[plainLen:]; len(recvBuf) != 0; {
		read, err = cah.socket.Read(recvBuf)
		if err != nil {
			return nil, err
		} else {
			recvBuf = recvBuf[read:]
		}
	}
	plaintext, ok := secretbox.Open(msgBuf[:0], msgBuf[plainLen:], cah.nonceAryIn, cah.sessionKey)
	if !ok {
		return nil, fmt.Errorf("Unable to decrypt message")
	}
	seg, _, err := capn.ReadFromMemoryZeroCopy(plaintext)
	return seg, err
}
Пример #5
0
// Decrypt decrypts an encrypted message and returns it (plaintext).
// If you have enabled compression, it wil detect it and decompress
// the msg after decrypting it.
func (c SaltSecret) Decrypt(msg []byte) ([]byte, error) {
	if len(msg) < nonceSize+secretbox.Overhead {
		return nil, errors.New("encrypted message length too short")
	}

	nonce := new([nonceSize]byte)
	copy(nonce[:], msg[:nonceSize])

	key, err := scrypt.Key(c.key, nonce[:], 2<<c.NPow, 8, 1, keySize)
	if err != nil {
		return nil, err
	}

	naclKey := new([keySize]byte)
	copy(naclKey[:], key)
	out, ok := secretbox.Open(nil, msg[nonceSize:], nonce, naclKey)
	if !ok {
		return nil, errors.New("could not decrypt message")
	}

	if nonce[23]&compressBit == compressBit {
		r, err := zlib.NewReader(bytes.NewReader(out))
		if err != nil {
			return nil, err
		}
		r.Close()
		out, err = ioutil.ReadAll(r)
		if err != nil {
			return nil, err
		}
	}
	return out, nil
}
Пример #6
0
func (p *AWSProvider) KeyDecrypt(data []byte) ([]byte, error) {
	var e *envelope

	err := json.Unmarshal(data, &e)
	if err != nil {
		return nil, err
	}

	if len(e.EncryptedKey) == 0 {
		return nil, fmt.Errorf("invalid ciphertext")
	}

	res, err := p.kms().Decrypt(&kms.DecryptInput{
		CiphertextBlob: e.EncryptedKey,
	})
	if err != nil {
		return nil, err
	}

	var key [KeyLength]byte
	copy(key[:], res.Plaintext[0:KeyLength])

	var nonce [NonceLength]byte
	copy(nonce[:], e.Nonce[0:NonceLength])

	var dec []byte

	dec, ok := secretbox.Open(dec, e.Ciphertext, &nonce, &key)
	if !ok {
		return nil, fmt.Errorf("failed decryption")
	}

	return dec, nil
}
Пример #7
0
func (nd *NaClDecryptor) decrypt(buf []byte) ([]byte, bool) {
	seqNoAndDF := binary.BigEndian.Uint64(buf[:8])
	df := (seqNoAndDF & (1 << 63)) != 0
	seqNo := seqNoAndDF & ((1 << 63) - 1)
	var di *NaClDecryptorInstance
	if df {
		di = nd.instanceDF
	} else {
		di = nd.instance
	}
	binary.BigEndian.PutUint64(di.nonce[16:24], seqNoAndDF)
	result, success := secretbox.Open(nil, buf[8:], &di.nonce, nd.sessionKey)
	if !success {
		return nil, false
	}
	// Drop duplicates. We do this *after* decryption since we must
	// not advance our state unless decryption succeeded. Doing so
	// would open an easy attack vector where an adversary could
	// inject a packet with a sequence number of (1 << 63) - 1,
	// causing all subsequent genuine packets to get dropped.
	offset, usedOffsets := di.advanceState(seqNo)
	if usedOffsets == nil || usedOffsets.Contains(offset) {
		// We have detected a possible replay attack, but it is
		// possible we may have just received a very old packet, or
		// duplication may have occurred in the network. So let's just
		// drop the packet silently.
		return nil, true
	}
	usedOffsets.Add(offset)
	return result, success
}
Пример #8
0
// Current implements storage.Vault.
func (v *vault) Current() (*sf.KeyPair, error) {
	var keyPair sf.KeyPair
	err := v.db.View(func(tx *bolt.Tx) error {
		logBucket := tx.Bucket([]byte("log"))
		if logBucket == nil {
			return errgo.New("empty vault")
		}

		seqBytes, encBytes := logBucket.Cursor().Last()
		if seqBytes == nil {
			return errgo.New("empty vault")
		}
		seq := new(sf.Nonce)
		copy(seq[:], seqBytes)
		keyPairBytes, ok := secretbox.Open(nil, encBytes, (*[24]byte)(seq), (*[32]byte)(v.secretKey))
		if !ok {
			seq := new(big.Int)
			seq.SetBytes(seqBytes)
			return errgo.Newf("error opening key pair #%s", seq.String())
		}
		keyPair.PublicKey = new(sf.PublicKey)
		copy(keyPair.PublicKey[:], keyPairBytes[:32])
		keyPair.PrivateKey = new(sf.PrivateKey)
		copy(keyPair.PrivateKey[:], keyPairBytes[32:])
		// TODO: mprotect private key
		// TODO: zeroize keyPairBytes

		return nil
	})
	if err != nil {
		return nil, errgo.Mask(err)
	}
	return &keyPair, nil
}
Пример #9
0
// Decrypt decrypts a payload and returns the decrypted plaintext.
func Decrypt(cypherBase64 []byte, nonceBase64 string, key []byte) ([]byte, error) {
	var plaintext []byte

	nonceText := make([]byte, base64.StdEncoding.DecodedLen(len(nonceBase64)))
	_, err := base64.StdEncoding.Decode(nonceText, []byte(nonceBase64))
	if err != nil {
		return nil, err
	}

	cypherText := make([]byte, base64.StdEncoding.DecodedLen(len(cypherBase64)))
	cypherLen, err := base64.StdEncoding.Decode(cypherText, cypherBase64)
	if err != nil {
		return nil, err
	}

	nonceArray := &[nonceLen]byte{}
	copy(nonceArray[:], nonceText[:nonceLen])

	encKey := &[keyLen]byte{}
	copy(encKey[:], key)

	plaintext, ok := secretbox.Open(plaintext, cypherText[:cypherLen], nonceArray, encKey)
	if !ok {
		return nil, fmt.Errorf("Error decrypting")
	}
	return plaintext, nil
}
Пример #10
0
func OpenReader(r io.Reader, passphrase []byte) (Key, io.Reader, error) {
	dec := json.NewDecoder(r)
	var key Key
	if err := dec.Decode(&key); err != nil {
		return key, nil, err
	}
	if err := key.Populate(passphrase, 32); err != nil {
		return key, nil, err
	}
	box, err := ioutil.ReadAll(io.MultiReader(dec.Buffered(), r))
	if err != nil {
		return key, nil, err
	}
	box = box[1:] // trim \n of json.Encoder.Encode
	out := make([]byte, 0, len(box)-secretbox.Overhead)
	var (
		nonce [24]byte
		k     [32]byte
	)
	copy(nonce[:], key.Salt)
	copy(k[:], key.Bytes)
	data, ok := secretbox.Open(out, box, &nonce, &k)
	if !ok {
		return key, nil, errors.New("failed open box")
	}
	return key, bytes.NewReader(data), nil

}
Пример #11
0
// read data into internal buffer - call with fh.mu held
func (fh *decrypter) fillBuffer() (err error) {
	// FIXME should overlap the reads with a go-routine and 2 buffers?
	readBuf := fh.readBuf
	n, err := io.ReadFull(fh.rc, readBuf)
	if err == io.EOF {
		// ReadFull only returns n=0 and EOF
		return io.EOF
	} else if err == io.ErrUnexpectedEOF {
		// Next read will return EOF
	} else if err != nil {
		return err
	}
	// Check header + 1 byte exists
	if n <= blockHeaderSize {
		return ErrorEncryptedFileBadHeader
	}
	// Decrypt the block using the nonce
	block := fh.buf
	_, ok := secretbox.Open(block[:0], readBuf[:n], fh.nonce.pointer(), &fh.c.dataKey)
	if !ok {
		// if block wouldn't decode and got unexpected EOF
		// then return that as it is probably a better error
		if err != nil {
			return err
		}
		return ErrorEncryptedBadBlock
	}
	fh.bufIndex = 0
	fh.bufSize = n - blockHeaderSize
	fh.nonce.increment()
	return nil
}
Пример #12
0
// Decrypt decrypts the encrypted key.
func (k *Kms) Decrypt(blob []byte) ([]byte, error) {
	var ev Envelope
	err := unmarshalJSON(blob, &ev)
	if err != nil {
		return nil, err
	}
	res, err := k.client.Decrypt(&kms.DecryptInput{
		CiphertextBlob: ev.EncryptedKey,
	})
	log.Printf("[DEBUG] Amazon KMS %s", awsutil.Prettify(res))
	if err != nil {
		return nil, err
	}

	var key [keyLength]byte
	copy(key[:], res.Plaintext[0:keyLength])

	var nonce [nonceLength]byte
	copy(nonce[:], ev.Nonce[0:nonceLength])

	var dec []byte
	dec, ok := secretbox.Open(dec, ev.Ciphertext, &nonce, &key)
	if !ok {
		return nil, fmt.Errorf("Can't decrypt data")
	}
	return dec, nil
}
Пример #13
0
func (ds *decryptStream) processEncryptionBlock(bl *EncryptionBlock) ([]byte, error) {

	blockNum := encryptionBlockNumber(bl.seqno - 1)

	if err := blockNum.check(); err != nil {
		return nil, err
	}

	nonce := ds.nonce.ForPayloadBox(blockNum)
	ciphertext := bl.PayloadCiphertext
	hash := sha512.Sum512(ciphertext)

	hashBox := ds.tagKey.Box(nonce, hash[:])
	ourAuthenticator := hashBox[:secretbox.Overhead]

	if !hmac.Equal(ourAuthenticator, bl.HashAuthenticators[ds.position]) {
		return nil, ErrBadTag(bl.seqno)
	}

	plaintext, ok := secretbox.Open([]byte{}, ciphertext, (*[24]byte)(nonce), (*[32]byte)(ds.payloadKey))
	if !ok {
		return nil, ErrBadCiphertext(bl.seqno)
	}

	// The encoding of the empty buffer implies the EOF.  But otherwise, all mechanisms are the same.
	if len(plaintext) == 0 {
		return nil, nil
	}
	return plaintext, nil
}
Пример #14
0
// Decrypt decrypts the encrypted message given the key associated with the Crypto object and
// returns, if successful, the plaintext message.
func (ic *Crypto) Decrypt(message string) (string, bool) {
	s := strings.Split(message, "@")

	// Sanity Check the Structure
	if len(s) != 2 {
		return "Structure is invalid.", false
	}

	// Decode the Nonce
	var nonce [24]byte
	decodednonce, err := base64.StdEncoding.DecodeString(s[1])
	if err != nil {
		return "Cannot base64 decode nonce", false
	}
	copy(nonce[:], decodednonce)

	// Decode the Message
	encrypted, err := base64.StdEncoding.DecodeString(s[0])
	if err != nil {
		return "Cannot base64 decode message", false
	}

	var decrypted []byte
	decrypted, success := secretbox.Open(decrypted, []byte(encrypted), &nonce, &ic.key)
	if !success {
		return "Failed to decrypt", false
	}
	return string(decrypted), true
}
Пример #15
0
func (kx *KeyExchange) exchange2() ([]byte, error) {
	reply, err := kx.meetingPlace.Exchange(kx.Log, kx.meeting2[:], kx.message2[:], kx.ShutdownChan)
	if err != nil {
		return nil, err
	}

	var nonce [24]byte
	if len(reply) < len(nonce) {
		return nil, errors.New("panda: meeting point reply too small")
	}

	if kx.sharedKey[0] == 0 && kx.sharedKey[1] == 0 {
		panic("here")
	}
	copy(nonce[:], reply)
	message, ok := secretbox.Open(nil, reply[24:], &nonce, &kx.sharedKey)
	if !ok {
		return nil, errors.New("panda: peer's message cannot be authenticated")
	}

	if len(message) < 4 {
		return nil, errors.New("panda: peer's message is invalid")
	}
	l := binary.LittleEndian.Uint32(message)
	message = message[4:]
	if l > uint32(len(message)) {
		return nil, errors.New("panda: peer's message is truncated")
	}
	message = message[:int(l)]
	return message, nil
}
Пример #16
0
func (b *EncryptBackend) Get(hash string) (data []byte, err error) {
	ref, _ := b.index[hash]
	enc, err := b.dest.Get(ref)
	if err != nil {
		return data, err
	}
	box := enc[headerSize:]
	var nonce [24]byte
	encData := make([]byte, len(box)-24)
	copy(nonce[:], box[:24])
	copy(encData[:], box[24:])
	out := make([]byte, len(box)-24)
	out, success := secretbox.Open(nil, encData, &nonce, b.key)
	if !success {
		return data, fmt.Errorf("failed to decrypt blob %v/%v", hash, ref)
	}
	// Decode snappy data
	data, err = snappy.Decode(nil, out)
	if err != nil {
		return data, fmt.Errorf("failed to decode blob %v/%v", hash, ref)
	}
	blobsDownloaded.Add(b.dest.String(), 1)
	bytesDownloaded.Add(b.dest.String(), int64(len(enc)))
	return
}
Пример #17
0
// CONTRACT: data smaller than dataMaxSize is read atomically.
func (sc *SecretConnection) Read(data []byte) (n int, err error) {
	if 0 < len(sc.recvBuffer) {
		n_ := copy(data, sc.recvBuffer)
		sc.recvBuffer = sc.recvBuffer[n_:]
		return
	}

	sealedFrame := make([]byte, sealedFrameSize)
	_, err = io.ReadFull(sc.conn, sealedFrame)
	if err != nil {
		return
	}

	// decrypt the frame
	var frame = make([]byte, totalFrameSize)
	// fmt.Printf("secretbox.Open(sealed:%X,recvNonce:%X,shrSecret:%X\n", sealedFrame, sc.recvNonce, sc.shrSecret)
	_, ok := secretbox.Open(frame[:0], sealedFrame, sc.recvNonce, sc.shrSecret)
	if !ok {
		return n, errors.New("Failed to decrypt SecretConnection")
	}
	incr2Nonce(sc.recvNonce)
	// end decryption

	var chunkLength = binary.BigEndian.Uint16(frame) // read the first two bytes
	if chunkLength > dataMaxSize {
		return 0, errors.New("chunkLength is greater than dataMaxSize")
	}
	var chunk = frame[dataLenSize : dataLenSize+chunkLength]

	n = copy(data, chunk)
	sc.recvBuffer = chunk[n:]
	return
}
Пример #18
0
Файл: reop.go Проект: seokj/reop
func decodeSeckey(seckeydata string) *Seckey {
	lines := strings.Split(seckeydata, "\n")
	var ident string
	fmt.Sscanf(lines[1], "ident:%s", &ident)
	b64 := strings.Join(lines[2:6], "\n")
	data, _ := base64.StdEncoding.DecodeString(b64)
	buf := bytes.NewBuffer(data)
	seckey := new(Seckey)
	buf.Read(seckey.sigalg[:])
	buf.Read(seckey.encalg[:])
	buf.Read(seckey.symalg[:])
	buf.Read(seckey.kdfalg[:])
	buf.Read(seckey.randomid[:])
	binary.Read(buf, binary.BigEndian, &seckey.kdfrounds)
	buf.Read(seckey.salt[:])
	buf.Read(seckey.nonce[:])
	buf.Read(seckey.tag[:])
	buf.Read(seckey.sigkey[:])
	buf.Read(seckey.enckey[:])
	// XXX use a real key
	var symkey [32]byte
	var enc [16 + 64 + 32]byte
	copy(enc[0:16], seckey.tag[:])
	copy(enc[16:80], seckey.sigkey[:])
	copy(enc[80:112], seckey.enckey[:])
	dec, ok := secretbox.Open(nil, enc[:], &seckey.nonce, &symkey)
	if !ok {
		log.Fatal("decryption failed")
	}
	copy(seckey.sigkey[:], dec[0:64])
	copy(seckey.enckey[:], dec[64:96])
	seckey.ident = ident
	return seckey
}
Пример #19
0
func (ds *decryptStream) processEncryptionBlock(bl *encryptionBlock) ([]byte, error) {

	blockNum := encryptionBlockNumber(bl.seqno - 1)

	if err := blockNum.check(); err != nil {
		return nil, err
	}

	nonce := nonceForChunkSecretBox(blockNum)
	ciphertext := bl.PayloadCiphertext

	// Check the authenticator.
	hashToAuthenticate := computePayloadHash(ds.headerHash, nonce, ciphertext)
	ourAuthenticator := hmacSHA512256(ds.macKey, hashToAuthenticate)
	if !hmac.Equal(ourAuthenticator, bl.HashAuthenticators[ds.position]) {
		return nil, ErrBadTag(bl.seqno)
	}

	plaintext, ok := secretbox.Open([]byte{}, ciphertext, (*[24]byte)(nonce), (*[32]byte)(ds.payloadKey))
	if !ok {
		return nil, ErrBadCiphertext(bl.seqno)
	}

	// The encoding of the empty buffer implies the EOF.  But otherwise, all mechanisms are the same.
	if len(plaintext) == 0 {
		return nil, nil
	}
	return plaintext, nil
}
Пример #20
0
// Decrypt data
//
// This function decrypts data originally encrypted using Encrypt(). It will extract
// the scrypt salt and nonce and apply the required transformations. An error is
// returned when the ciphertext is too short or the password does not match. Otherwise,
// the raw decrypted message is returned.
func (b *Boxer) Decrypt(ciphertext []byte, password []byte) ([]byte, error) {
	minLength := SaltLength + NonceLength + secretbox.Overhead + 1

	if len(ciphertext) < minLength {
		return nil, fmt.Errorf("The ciphertext is too short (%d bytes) to be valid. It needs to be at least %d bytes.", len(ciphertext), minLength)
	}

	// figure out the salt to derive the key used for encryption
	salt := new([SaltLength]byte)
	copy(salt[:], ciphertext[:SaltLength])

	key, err := b.DeriveKey(password, salt)
	if err != nil {
		return nil, err
	}

	// find the secretbox nonce (if follows the SaltLength bytes at the beginning of ciphertext)
	nonce := new([NonceLength]byte)
	copy(nonce[:], ciphertext[SaltLength:(SaltLength+NonceLength)])

	// slice out the secretbox
	box := ciphertext[(SaltLength + NonceLength):]

	// ... and open it
	plain, success := secretbox.Open(nil, box, nonce, key)
	if !success {
		return nil, errors.New("Decrypting failed, probably due to a wrong password.")
	}

	return plain, nil
}
Пример #21
0
// Decrypt returns plaintext from ciphertext
func Decrypt(key *[KeySize]byte, nonce *[NonceSize]byte, ciphertext []byte) ([]byte, error) {
	plaintext, ok := secretbox.Open(nil, ciphertext, nonce, key)
	if !ok {
		return nil, errors.New("Could not decrypt")
	}
	return plaintext, nil
}
Пример #22
0
// Read as per io.Reader
func (fh *decrypter) Read(p []byte) (n int, err error) {
	if fh.err != nil {
		return 0, fh.err
	}
	if fh.bufIndex >= fh.bufSize {
		// Read data
		// FIXME should overlap the reads with a go-routine and 2 buffers?
		readBuf := fh.readBuf
		n, err = io.ReadFull(fh.rc, readBuf)
		if err == io.EOF {
			// ReadFull only returns n=0 and EOF
			return 0, fh.finish(io.EOF)
		} else if err == io.ErrUnexpectedEOF {
			// Next read will return EOF
		} else if err != nil {
			return 0, fh.finish(err)
		}
		// Check header + 1 byte exists
		if n <= blockHeaderSize {
			return 0, fh.finish(ErrorEncryptedFileBadHeader)
		}
		// Decrypt the block using the nonce
		block := fh.buf
		_, ok := secretbox.Open(block[:0], readBuf[:n], fh.nonce.pointer(), &fh.c.dataKey)
		if !ok {
			return 0, fh.finish(ErrorEncryptedBadBlock)
		}
		fh.bufIndex = 0
		fh.bufSize = n - blockHeaderSize
		fh.nonce.increment()
	}
	n = copy(p, fh.buf[fh.bufIndex:fh.bufSize])
	fh.bufIndex += n
	return n, nil
}
Пример #23
0
func (ds *decryptStream) processEncryptionHeader(hdr *EncryptionHeader) error {
	if err := hdr.validate(); err != nil {
		return err
	}

	ephemeralKey := ds.ring.ImportEphemeralKey(hdr.Ephemeral)
	if ephemeralKey == nil {
		return ErrBadEphemeralKey
	}

	ds.nonce = NewNonceForEncryption(ephemeralKey)

	var secretKey BoxSecretKey
	var err error

	secretKey, ds.tagKey, ds.payloadKey, ds.position, err = ds.tryVisibleReceivers(hdr, ephemeralKey)
	if err != nil {
		return err
	}
	if secretKey == nil {
		secretKey, ds.tagKey, ds.payloadKey, ds.position, err = ds.tryHiddenReceivers(hdr, ephemeralKey)
		ds.mki.ReceiverIsAnon = true
	}
	if err != nil {
		return err
	}
	if secretKey == nil || ds.position < 0 {
		return ErrNoDecryptionKey
	}
	ds.mki.ReceiverKey = secretKey

	// Decrypt the sender's public key
	senderKeySlice, ok := secretbox.Open([]byte{}, hdr.SenderSecretbox, (*[24]byte)(ds.nonce), (*[32]byte)(ds.payloadKey))
	if !ok {
		return ErrBadSenderKeySecretbox
	}
	ds.senderKey, err = rawBoxKeyFromSlice(senderKeySlice)
	if err != nil {
		return err
	}

	// Lookup the sender's public key in our keyring, and import
	// it for use. However, if the sender key is the same as the ephemeral
	// key, then assume "anonymous mode", so use the already imported anonymous
	// key.
	if !hmac.Equal(hdr.Ephemeral, ds.senderKey[:]) {
		longLivedSenderKey := ds.ring.LookupBoxPublicKey(ds.senderKey[:])
		if longLivedSenderKey == nil {
			return ErrNoSenderKey
		}
		ds.tagKey = secretKey.Precompute(longLivedSenderKey)
		ds.mki.SenderKey = longLivedSenderKey
	} else {
		ds.mki.SenderIsAnon = true
		ds.mki.SenderKey = ephemeralKey
	}

	return nil
}
Пример #24
0
func download(key string, password string) {
	fmt.Println("Downloading file")

	cipher_key := sha256.Sum256([]byte(password))

	uri, err := url.ParseRequestURI(BASE_URL)
	uri.Path = "/api/download"
	query_parameters := url.Values{}
	query_parameters.Set("key", key)
	uri.RawQuery = query_parameters.Encode()
	url_str := fmt.Sprintf("%v", uri)

	res, err := http.Get(url_str)
	if err != nil {
		oopsie(err.Error())
	}
	defer res.Body.Close()

	decoder := json.NewDecoder(res.Body)
	var jsondata Download_info
	err = decoder.Decode(&jsondata)
	if err != nil {
		oopsie(err.Error())
	}

	url := jsondata.Url
	res, err = http.Get(url)
	if err != nil {
		oopsie(err.Error())
	}
	defer res.Body.Close()

	encoded_metadata := res.Header.Get("x-amz-meta-filename")
	metadata, err := base64.StdEncoding.DecodeString(encoded_metadata)
	if err != nil {
		oopsie(err.Error())
	}

	var nonce [NONCE_SIZE]byte
	copy(nonce[:], metadata)
	filename_bytes, ok := secretbox.Open(nil, metadata[NONCE_SIZE:], &nonce, &cipher_key)
	if !ok { // Thanks for returning a bool instead of an error object :( Super intuitive!
		oopsie(err.Error())
	}
	filename := string(filename_bytes)

	file, err := os.Create(filename)
	if err != nil {
		oopsie(err.Error())
	}
	defer file.Close()

	_, err = io.Copy(file, res.Body)
	if err != nil {
		oopsie(err.Error())
	}

	fmt.Printf("File saved as '%v'\n", filename)
}
Пример #25
0
// Decrypt extracts the nonce from the ciphertext, and attempts to
// decrypt with NaCl's secretbox.
func Decrypt(key *[KeySize]byte, in []byte) ([]byte, bool) {
	if len(in) < nonceSize {
		return nil, false
	}
	var nonce [nonceSize]byte
	copy(nonce[:], in)
	return secretbox.Open(nil, in[nonceSize:], &nonce, key)
}
Пример #26
0
func (receiver *EncryptedTCPReceiver) Decode(msg []byte) ([]byte, error) {
	decodedMsg, success := secretbox.Open(nil, msg, &receiver.state.nonce, receiver.state.sessionKey)
	if !success {
		return nil, fmt.Errorf("Unable to decrypt TCP msg")
	}
	receiver.state.advance()
	return decodedMsg, nil
}
Пример #27
0
// trySavedKeys tries to decrypt ciphertext using keys saved for missing messages.
func (r *Ratchet) trySavedKeysAndCheckAuth(authTag, authBody, ciphertext []byte) ([]byte, error) {
	if len(ciphertext) < sealedHeaderSize {
		return nil, errors.New("ratchet: header too small to be valid")
	}

	sealedHeader := ciphertext[:sealedHeaderSize]
	var nonce [24]byte
	copy(nonce[:], sealedHeader)
	sealedHeader = sealedHeader[len(nonce):]

	for headerKey, messageKeys := range r.saved {
		header, ok := secretbox.Open(nil, sealedHeader, &nonce, &headerKey)
		if !ok {
			continue
		}
		if len(header) != headerSize {
			continue
		}
		msgNum := binary.LittleEndian.Uint32(header[:4])
		msgKey, ok := messageKeys[msgNum]
		if !ok {
			// This is a fairly common case: the message key might
			// not have been saved because it's the next message
			// key.
			return nil, nil
		}

		sealedMessage := ciphertext[sealedHeaderSize:]
		copy(nonce[:], header[nonceInHeaderOffset:])
		msg, ok := secretbox.Open(nil, sealedMessage, &nonce, &msgKey.key)
		if !ok {
			return nil, errors.New("ratchet: corrupt message")
		}
		if err := r.CheckAuth(authTag, authBody, msg, &msgKey.authPriv); err != nil {
			return nil, err
		}
		delete(messageKeys, msgNum)
		if len(messageKeys) == 0 {
			delete(r.saved, headerKey)
		}
		return msg, nil
	}

	return nil, nil
}
Пример #28
0
// ReadJSON returns the decoded configuration file, or an error.
func ReadJSON(secustom string) (configger Config, err error) {
	naclKey := new([keySize]byte)
	copy(naclKey[:], pad[:keySize])
	nonce := new([nonceSize]byte)
	in, err := ioutil.ReadFile(secustom)
	if err != nil {
		return configger, err
	}
	copy(nonce[:], in[:nonceSize])
	configbytes, ok := secretbox.Open(nil, in[nonceSize:], nonce, naclKey)

	if ok {

		err = json.Unmarshal(configbytes, &configger)
		if err == nil {
			// No password. Success.
			return configger, nil
		}
	}

	// The blank password didn't work. Ask the user via speakeasy
	configlock, err := speakeasy.Ask("Password: "******"Could not decrypt the config file. Wrong password?")
	}

	err = json.Unmarshal(configbytes, &configger)
	if err != nil {
		return configger, err
	}
	return configger, nil

}
Пример #29
0
func (sch *SChannel) decrypt(in []byte) ([]byte, bool) {
	if len(in) <= nonceSize {
		return nil, false
	}

	var nonce [nonceSize]byte
	copy(nonce[:], in[:nonceSize])
	return secretbox.Open(nil, in[nonceSize:], &nonce, &sch.rkey)
}
Пример #30
0
func (s *registrationSuite) openBox(c *gc.C, ciphertext, nonce, key []byte) []byte {
	var nonceArray [24]byte
	var keyArray [32]byte
	c.Assert(copy(nonceArray[:], nonce), gc.Equals, len(nonceArray))
	c.Assert(copy(keyArray[:], key), gc.Equals, len(keyArray))
	message, ok := secretbox.Open(nil, ciphertext, &nonceArray, &keyArray)
	c.Assert(ok, jc.IsTrue)
	return message
}