本文整理汇总了Golang中golang.org/x/crypto/nacl/secretbox.Open函数的典型用法代码示例。如果您正苦于以下问题:Golang Open函数的具体用法?Golang Open怎么用?Golang Open使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Open函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Source
// 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: Decrypt
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: processEncryptionBlock
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: readAndDecryptOne
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: Decrypt
// 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: KeyDecrypt
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: decrypt
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: Current
// 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: Decrypt
// 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: OpenReader
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: fillBuffer
// 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: Decrypt
// 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: processEncryptionBlock
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: Decrypt
// 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: exchange2
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
}