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