本文整理汇总了Golang中golang.org/x/crypto/nacl/secretbox.Open函数的典型用法代码示例。如果您正苦于以下问题:Golang Open函数的具体用法?Golang Open怎么用?Golang Open使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Open函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
}
开发者ID:vmware,项目名称:vic,代码行数:34,代码来源:secret.go
示例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
}
开发者ID:gmelika,项目名称:rack,代码行数:33,代码来源:crypt.go
示例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
}
开发者ID:polluks,项目名称:client,代码行数:33,代码来源:decrypt.go
示例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
}
开发者ID:chang290,项目名称:server,代码行数:29,代码来源:connection.go
示例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
}
开发者ID:andmarios,项目名称:crypto,代码行数:36,代码来源:saltsecret.go
示例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
}
开发者ID:convox,项目名称:rack,代码行数:34,代码来源:keys.go
示例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
}
开发者ID:codingbunch,项目名称:weave,代码行数:31,代码来源:frame_crypto.go
示例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
}
开发者ID:cmars,项目名称:shadowfax,代码行数:35,代码来源:vault.go
示例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
}
开发者ID:snikch,项目名称:api,代码行数:28,代码来源:crypt.go
示例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
}
开发者ID:rdterner,项目名称:go-1,代码行数:28,代码来源:secretboxhlp.go
示例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
}
开发者ID:ncw,项目名称:rclone,代码行数:33,代码来源:cipher.go
示例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
}
开发者ID:nlamirault,项目名称:enigma,代码行数:28,代码来源:kms.go
示例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
}
开发者ID:mark-adams,项目名称:client,代码行数:30,代码来源:decrypt.go
示例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
}
开发者ID:s-rah,项目名称:ivy,代码行数:31,代码来源:crypto.go
示例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
}
开发者ID:carriercomm,项目名称:pond,代码行数:31,代码来源:panda.go
示例16: Get
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
}
开发者ID:marsmensch,项目名称:blobstash,代码行数:25,代码来源:encrypt.go
示例17: Read
// 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
}
开发者ID:zramsay,项目名称:geth-tmsp,代码行数:34,代码来源:secret_connection.go
示例18: decodeSeckey
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
}
开发者ID:seokj,项目名称:reop,代码行数:34,代码来源:reop.go
示例19: processEncryptionBlock
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
}
开发者ID:qbit,项目名称:client,代码行数:29,代码来源:decrypt.go
示例20: Decrypt
// 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
}
开发者ID:xrstf,项目名称:boxer,代码行数:37,代码来源:boxer.go
注:本文中的golang.org/x/crypto/nacl/secretbox.Open函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论