本文整理汇总了Golang中golang.org/x/crypto/nacl/secretbox.Seal函数的典型用法代码示例。如果您正苦于以下问题:Golang Seal函数的具体用法?Golang Seal怎么用?Golang Seal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Seal函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: Encrypt
// Encrypt acts like append() but appends an encrypted version of msg to out.
func (r *Ratchet) Encrypt(out, msg []byte) []byte {
if r.ratchet {
r.randBytes(r.sendRatchetPrivate[:])
copy(r.sendHeaderKey[:], r.nextSendHeaderKey[:])
var sharedKey, keyMaterial [32]byte
curve25519.ScalarMult(&sharedKey, &r.sendRatchetPrivate, &r.recvRatchetPublic)
sha := sha256.New()
sha.Write(rootKeyUpdateLabel)
sha.Write(r.rootKey[:])
sha.Write(sharedKey[:])
if r.v2 {
sha.Sum(keyMaterial[:0])
h := hmac.New(sha256.New, keyMaterial[:])
deriveKey(&r.rootKey, rootKeyLabel, h)
deriveKey(&r.nextSendHeaderKey, sendHeaderKeyLabel, h)
deriveKey(&r.sendChainKey, chainKeyLabel, h)
} else {
sha.Sum(r.rootKey[:0])
h := hmac.New(sha256.New, r.rootKey[:])
deriveKey(&r.nextSendHeaderKey, sendHeaderKeyLabel, h)
deriveKey(&r.sendChainKey, chainKeyLabel, h)
}
r.prevSendCount, r.sendCount = r.sendCount, 0
r.ratchet = false
}
h := hmac.New(sha256.New, r.sendChainKey[:])
var messageKey [32]byte
deriveKey(&messageKey, messageKeyLabel, h)
deriveKey(&r.sendChainKey, chainKeyStepLabel, h)
var sendRatchetPublic [32]byte
curve25519.ScalarBaseMult(&sendRatchetPublic, &r.sendRatchetPrivate)
var header [headerSize]byte
var headerNonce, messageNonce [24]byte
r.randBytes(headerNonce[:])
r.randBytes(messageNonce[:])
binary.LittleEndian.PutUint32(header[0:4], r.sendCount)
binary.LittleEndian.PutUint32(header[4:8], r.prevSendCount)
copy(header[8:], sendRatchetPublic[:])
copy(header[nonceInHeaderOffset:], messageNonce[:])
out = append(out, headerNonce[:]...)
out = secretbox.Seal(out, header[:], &headerNonce, &r.sendHeaderKey)
r.sendCount++
return secretbox.Seal(out, msg, &messageNonce, &messageKey)
}
开发者ID:carriercomm,项目名称:pond,代码行数:50,代码来源:ratchet.go
示例2: sealBox
func sealBox(data []byte, key *secretkey.Key) []byte {
var nonce [24]byte
if _, err := rand.Read(nonce[:]); err != nil {
panic("rand.Read error: " + err.Error())
}
return secretbox.Seal(nonce[:], data, &nonce, (*[32]byte)(key))
}
开发者ID:nullren,项目名称:kebab,代码行数:7,代码来源:encrypted.go
示例3: Put
func (b *EncryptBackend) Put(hash string, rawData []byte) (err error) {
// #blobstash/secretbox\n
// data hash\n
// data
var nonce [24]byte
//out := make([]byte, len(data) + secretbox.Overhead + 24 + headerSize)
if err := GenerateNonce(&nonce); err != nil {
return err
}
// First we compress the data with snappy
data := snappy.Encode(nil, rawData)
var out bytes.Buffer
out.WriteString("#blobstash/secretbox\n")
out.WriteString(fmt.Sprintf("%v\n", hash))
encData := make([]byte, len(data)+secretbox.Overhead)
secretbox.Seal(encData[0:0], data, &nonce, b.key)
out.Write(nonce[:])
out.Write(encData)
encHash := fmt.Sprintf("%x", blake2b.Sum256(out.Bytes()))
b.dest.Put(encHash, out.Bytes())
b.Lock()
b.index[hash] = encHash
defer b.Unlock()
blobsUploaded.Add(b.dest.String(), 1)
bytesUploaded.Add(b.dest.String(), int64(len(out.Bytes())))
return
}
开发者ID:marsmensch,项目名称:blobstash,代码行数:28,代码来源:encrypt.go
示例4: Set
// Set encodes a session from v into a cookie on w.
// See encoding/json for encoding behavior.
func Set(w http.ResponseWriter, v interface{}, config *Config) error {
now := time.Now()
b, err := json.Marshal(v)
if err != nil {
return err
}
tb := make([]byte, len(b)+8)
binary.BigEndian.PutUint64(tb, uint64(now.Unix()))
copy(tb[8:], b)
var nonce [24]byte
_, err = rand.Read(nonce[:])
if err != nil {
return err
}
out := secretbox.Seal(nonce[:], tb, &nonce, config.Keys[0])
cookie := &http.Cookie{
Name: config.name(),
Value: base64.URLEncoding.EncodeToString(out),
Expires: now.Add(config.maxAge()),
Path: config.Path,
Domain: config.Domain,
Secure: config.Secure,
HttpOnly: config.HTTPOnly,
}
if cookie.Path == "" {
cookie.Path = "/"
}
s := cookie.String()
if len(s) > maxSize {
return ErrTooLong
}
w.Header().Add("Set-Cookie", s)
return nil
}
开发者ID:tomzhang,项目名称:tugboat,代码行数:36,代码来源:session.go
示例5: Encrypt
// Encrypt encrypt the text using a plaintext key
func (k *Kms) Encrypt(plaintext []byte) ([]byte, error) {
encKey, err := k.generateEnvelopKey(getKey())
var key [keyLength]byte
copy(key[:], encKey.Plaintext[0:keyLength])
rand, err := k.generateNonce()
if err != nil {
return nil, err
}
var nonce [nonceLength]byte
copy(nonce[:], rand[0:nonceLength])
var enc []byte
enc = secretbox.Seal(enc, plaintext, &nonce, &key)
ev := &Envelope{
Ciphertext: enc,
EncryptedKey: encKey.CiphertextBlob,
Nonce: nonce[:],
}
output, err := marshalJSON(ev)
if err != nil {
return nil, err
}
return output, nil
}
开发者ID:nlamirault,项目名称:enigma,代码行数:27,代码来源:kms.go
示例6: Encrypt
func (s *secretBox) Encrypt(key *[32]byte, data []byte) ([]byte, error) {
var nonce [24]byte
if _, err := rand.Read(nonce[:]); err != nil {
return nil, err
}
return secretbox.Seal(nonce[:], data, &nonce, key), nil
}
开发者ID:absurdhero,项目名称:secrets,代码行数:7,代码来源:secretbox.go
示例7: encryptBytes
func (es *encryptStream) encryptBytes(b []byte) error {
if err := es.numBlocks.check(); err != nil {
return err
}
nonce := es.nonce.ForPayloadBox(es.numBlocks)
ciphertext := secretbox.Seal([]byte{}, b, (*[24]byte)(nonce), (*[32]byte)(&es.payloadKey))
hash := sha512.Sum512(ciphertext)
block := EncryptionBlock{
PayloadCiphertext: ciphertext,
}
for _, tagKey := range es.tagKeys {
hashBox := tagKey.Box(nonce, hash[:])
authenticator := hashBox[:secretbox.Overhead]
block.HashAuthenticators = append(block.HashAuthenticators, authenticator)
}
if err := es.encoder.Encode(block); err != nil {
return err
}
es.numBlocks++
return nil
}
开发者ID:mark-adams,项目名称:client,代码行数:27,代码来源:encrypt.go
示例8: Encrypt
// Encrypt some data with a password
//
// This function automatically stretches the password to meet the KeyLength
// requirement, as well as calculate a fresh nonce. The function returns an
// error if the data/password is empty or not enough data is available in
// rand.Reader, otherwise the first value will be the encryption result,
// containing the salt and nonce.
func (b *Boxer) Encrypt(data []byte, password []byte) ([]byte, error) {
if len(data) == 0 {
return nil, errors.New("Cannot encrypt zero-length data.")
}
if len(password) == 0 {
return nil, errors.New("Empty passwords are not allowed for encryption.")
}
// derive a new encryption key for this message
key, salt, err := b.DeriveKeyFromPassword(password)
if err != nil {
return nil, errors.New("Could not derive encryption key from password: " + err.Error())
}
// create a fresh nonce
nonce, err := b.CreateNonce()
if err != nil {
return nil, errors.New("Could not create nonce: " + err.Error())
}
// seal the data in a nacl box; the box will have the kd salt and nonce prepended
box := make([]byte, SaltLength+NonceLength)
copy(box, salt[:])
copy(box[SaltLength:], nonce[:])
// let the magic happen
box = secretbox.Seal(box, data, nonce, key)
return box, nil
}
开发者ID:xrstf,项目名称:boxer,代码行数:38,代码来源:boxer.go
示例9: MarshalJSON
// MarshalJSON implements json.Marshaler interface.
func (s Secret) MarshalJSON() ([]byte, error) {
nonce := [length]byte{}
out := []byte{}
out = secretbox.Seal(out, []byte(s), &nonce, &Key)
res := append(nonce[:], out...)
return json.Marshal(res)
}
开发者ID:zemirco,项目名称:jsonbox,代码行数:8,代码来源:jsonbox.go
示例10: Read
// Read as per io.Reader
func (fh *encrypter) 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[:blockDataSize]
n, err = io.ReadFull(fh.in, readBuf)
if err == io.EOF {
// ReadFull only returns n=0 and EOF
return fh.finish(io.EOF)
} else if err == io.ErrUnexpectedEOF {
// Next read will return EOF
} else if err != nil {
return fh.finish(err)
}
// Write nonce to start of block
copy(fh.buf, fh.nonce[:])
// Encrypt the block using the nonce
block := fh.buf
secretbox.Seal(block[:0], readBuf[:n], fh.nonce.pointer(), &fh.c.dataKey)
fh.bufIndex = 0
fh.bufSize = blockHeaderSize + n
fh.nonce.increment()
}
n = copy(p, fh.buf[fh.bufIndex:fh.bufSize])
fh.bufIndex += n
return n, nil
}
开发者ID:marcopaganini,项目名称:rclone,代码行数:31,代码来源:cipher.go
示例11: Send
// Send implements TCPSender by sealing and sending the msg as-is.
func (sender *encryptedTCPSender) Send(msg []byte) error {
sender.Lock()
defer sender.Unlock()
encodedMsg := secretbox.Seal(nil, msg, &sender.state.nonce, sender.state.sessionKey)
sender.state.advance()
return sender.sender.Send(encodedMsg)
}
开发者ID:weaveworks,项目名称:mesh,代码行数:8,代码来源:protocol_crypto.go
示例12: Encode
// Encode encodes a single frame worth of payload and returns the encoded
// length. InvalidPayloadLengthError is recoverable, all other errors MUST be
// treated as fatal and the session aborted.
func (encoder *Encoder) Encode(frame, payload []byte) (n int, err error) {
payloadLen := len(payload)
if MaximumFramePayloadLength < payloadLen {
return 0, InvalidPayloadLengthError(payloadLen)
}
if len(frame) < payloadLen+FrameOverhead {
return 0, io.ErrShortBuffer
}
// Generate a new nonce.
var nonce [nonceLength]byte
if err = encoder.nonce.bytes(&nonce); err != nil {
return 0, err
}
encoder.nonce.counter++
// Encrypt and MAC payload.
box := secretbox.Seal(frame[:lengthLength], payload, &nonce, &encoder.key)
// Obfuscate the length.
length := uint16(len(box) - lengthLength)
lengthMask := encoder.drbg.NextBlock()
length ^= binary.BigEndian.Uint16(lengthMask)
binary.BigEndian.PutUint16(frame[:2], length)
// Return the frame.
return len(box), nil
}
开发者ID:OperatorFoundation,项目名称:obfs4,代码行数:31,代码来源:framing.go
示例13: sealBox
func (s *registrationSuite) sealBox(c *gc.C, nonce, key []byte, message string) []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))
return secretbox.Seal(nil, []byte(message), &nonceArray, &keyArray)
}
开发者ID:kat-co,项目名称:juju,代码行数:7,代码来源:registration_test.go
示例14: encryptBytes
func (pes *testEncryptStream) encryptBytes(b []byte) error {
if err := pes.numBlocks.check(); err != nil {
return err
}
nonce := pes.numBlocks.newCounterNonce()
if pes.options.corruptNonce != nil {
pes.options.corruptNonce(nonce, pes.numBlocks)
}
ciphertext := secretbox.Seal([]byte{}, b, (*[24]byte)(nonce), (*[32]byte)(&pes.sessionKey))
// Compute the MAC over the nonce and the ciphertext
sum := hashNonceAndAuthTag(nonce, ciphertext)
macs := pes.macForAllGroups(sum)
block := EncryptionBlock{
Version: PacketVersion1,
Tag: PacketTagEncryptionBlock,
Ciphertext: ciphertext,
MACs: macs,
}
if pes.options.corruptEncryptionBlock != nil {
pes.options.corruptEncryptionBlock(&block, pes.numBlocks)
}
if err := encodeNewPacket(pes.output, block); err != nil {
return nil
}
pes.numBlocks++
return nil
}
开发者ID:polluks,项目名称:client,代码行数:34,代码来源:tweakable_encryptor_test.go
示例15: LockUnsafe
// LockUnsafe Allow an application to store config with default/no password.
func LockUnsafe(path string, configbytes []byte, key []byte) (n int, err error) {
fmt.Printf("Writing %v bytes to %s\n", len(configbytes), path)
if configbytes == nil {
return 0, errors.New("seconf: No bytes to write")
}
if path == "" {
return 0, errors.New("seconf: Path can't be blank")
}
key = append(key, pad...)
naclKey := new([keySize]byte)
copy(naclKey[:], key[:keySize])
nonce := new([nonceSize]byte)
// Read bytes from random and put them in nonce until it is full.
_, err = io.ReadFull(rand.Reader, nonce[:])
if err != nil {
return 0, errors.New("Could not read from random: " + err.Error())
}
out := make([]byte, nonceSize)
copy(out, nonce[:])
out = secretbox.Seal(out, configbytes, nonce, naclKey)
err = ioutil.WriteFile(path, out, 0600)
if err != nil {
return 0, errors.New("Error while writing config file: " + err.Error())
}
return len(out), nil
}
开发者ID:aerth,项目名称:cosgo,代码行数:31,代码来源:seconf.go
示例16: Write
// Writes encrypted frames of `sealedFrameSize`
// CONTRACT: data smaller than dataMaxSize is read atomically.
func (sc *SecretConnection) Write(data []byte) (n int, err error) {
for 0 < len(data) {
var frame []byte = make([]byte, totalFrameSize)
var chunk []byte
if dataMaxSize < len(data) {
chunk = data[:dataMaxSize]
data = data[dataMaxSize:]
} else {
chunk = data
data = nil
}
chunkLength := len(chunk)
binary.BigEndian.PutUint16(frame, uint16(chunkLength))
copy(frame[dataLenSize:], chunk)
// encrypt the frame
var sealedFrame = make([]byte, sealedFrameSize)
secretbox.Seal(sealedFrame[:0], frame, sc.sendNonce, sc.shrSecret)
// fmt.Printf("secretbox.Seal(sealed:%X,sendNonce:%X,shrSecret:%X\n", sealedFrame, sc.sendNonce, sc.shrSecret)
incr2Nonce(sc.sendNonce)
// end encryption
_, err := sc.conn.Write(sealedFrame)
if err != nil {
return n, err
} else {
n += len(chunk)
}
}
return
}
开发者ID:zramsay,项目名称:geth-tmsp,代码行数:33,代码来源:secret_connection.go
示例17: encryptBytes
func (es *encryptStream) encryptBytes(b []byte) error {
if err := es.numBlocks.check(); err != nil {
return err
}
nonce := nonceForChunkSecretBox(es.numBlocks)
ciphertext := secretbox.Seal([]byte{}, b, (*[24]byte)(nonce), (*[32]byte)(&es.payloadKey))
block := encryptionBlock{
PayloadCiphertext: ciphertext,
}
// Compute the digest to authenticate, and authenticate it for each
// recipient.
hashToAuthenticate := computePayloadHash(es.headerHash, nonce, ciphertext)
for _, macKey := range es.macKeys {
authenticator := hmacSHA512256(macKey, hashToAuthenticate)
block.HashAuthenticators = append(block.HashAuthenticators, authenticator)
}
if err := es.encoder.Encode(block); err != nil {
return err
}
es.numBlocks++
return nil
}
开发者ID:qbit,项目名称:client,代码行数:28,代码来源:encrypt.go
示例18: Encrypt
// Encrypt encrypts a message and returns the encrypted msg (nonce + ciphertext).
// If you have enabled compression, it will compress the msg before encrypting it.
func (c SaltSecret) Encrypt(msg []byte) (out []byte, e error) {
nonce := new([nonceSize]byte)
_, err := io.ReadFull(rand.Reader, nonce[:])
if err != nil {
return nil, err
}
// We use the last bit of the nonce as a compression indicator.
// This should still keep you safe (extremely rare collisions).
nonce[23] &= ^compressBit
if c.compress {
nonce[23] |= compressBit
}
key, err := scrypt.Key(c.key, nonce[:], 2<<c.NPow, 8, 1, keySize)
if err != nil {
return nil, err
}
if c.compress {
var b bytes.Buffer
w := zlib.NewWriter(&b)
w.Write(msg)
w.Close()
msg = b.Bytes()
}
out = make([]byte, nonceSize)
copy(out, nonce[:])
naclKey := new([keySize]byte)
copy(naclKey[:], key)
out = secretbox.Seal(out, msg, nonce, naclKey)
return out, nil
}
开发者ID:andmarios,项目名称:crypto,代码行数:36,代码来源:saltsecret.go
示例19: exchange1
func (kx *KeyExchange) exchange1() error {
reply, err := kx.meetingPlace.Exchange(kx.Log, kx.meeting1[:], kx.message1[:], kx.ShutdownChan)
if err != nil {
return err
}
var peerDHPublic, encryptedPeerDHPublic [32]byte
if len(reply) < len(encryptedPeerDHPublic) {
return errors.New("panda: meeting point reply too small")
}
copy(encryptedPeerDHPublic[:], reply)
rijndael.NewCipher(&kx.key).Decrypt(&peerDHPublic, &encryptedPeerDHPublic)
curve25519.ScalarMult(&kx.sharedKey, &kx.dhPrivate, &peerDHPublic)
paddedLen := kx.meetingPlace.Padding()
padded := make([]byte, paddedLen-24 /* nonce */ -secretbox.Overhead)
binary.LittleEndian.PutUint32(padded, uint32(len(kx.kxBytes)))
copy(padded[4:], kx.kxBytes)
if _, err := io.ReadFull(kx.rand, padded[4+len(kx.kxBytes):]); err != nil {
return err
}
var nonce [24]byte
if _, err := io.ReadFull(kx.rand, nonce[:]); err != nil {
return err
}
kx.message2 = make([]byte, paddedLen)
copy(kx.message2, nonce[:])
secretbox.Seal(kx.message2[24:24], padded, &nonce, &kx.sharedKey)
return nil
}
开发者ID:carriercomm,项目名称:pond,代码行数:35,代码来源:panda.go
示例20: Encrypt
// Encrypt returns ciphertext from plaintext
func Encrypt(key *[KeySize]byte, nonce *[NonceSize]byte, plaintext []byte) ([]byte, error) {
ciphertext := make([]byte, len(nonce))
copy(ciphertext, nonce[:])
ciphertext = secretbox.Seal(ciphertext, plaintext, nonce, key)
return ciphertext, nil
}
开发者ID:hink,项目名称:go-nacl,代码行数:8,代码来源:secretbox.go
注:本文中的golang.org/x/crypto/nacl/secretbox.Seal函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论