当前位置: 首页>>代码示例>>Golang>>正文


Golang poly1305.Sum函数代码示例

本文整理汇总了Golang中golang.org/x/crypto/poly1305.Sum函数的典型用法代码示例。如果您正苦于以下问题:Golang Sum函数的具体用法?Golang Sum怎么用?Golang Sum使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Sum函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Chaff

// Chaff the data. noncePrfx is 64-bit nonce. Output data will be much
// larger: 256 bytes for each input byte.
func Chaff(authKey *[32]byte, noncePrfx, in []byte) []byte {
	out := make([]byte, len(in)*EnlargeFactor)
	keys := make([]byte, 8*64)
	nonce := make([]byte, 24)
	copy(nonce[:8], noncePrfx)
	var i int
	var v byte
	tag := new([16]byte)
	macKey := new([32]byte)
	for n, b := range in {
		binary.BigEndian.PutUint64(nonce[16:], uint64(n))
		salsa20.XORKeyStream(keys, keys, nonce, authKey)
		for i = 0; i < 8; i++ {
			v = (b >> uint8(i)) & 1
			copy(macKey[:], keys[64*i:64*i+32])
			if v == 0 {
				poly1305.Sum(tag, []byte("1"), macKey)
			} else {
				poly1305.Sum(tag, []byte("0"), macKey)
			}
			copy(out[16*(n*16+i*2):], tag[:])
			copy(macKey[:], keys[64*i+32:64*i+64])
			if v == 1 {
				poly1305.Sum(tag, []byte("1"), macKey)
			} else {
				poly1305.Sum(tag, []byte("0"), macKey)
			}
			copy(out[16*(n*16+i*2+1):], tag[:])
		}
		zero(keys)
	}
	zero(macKey[:])
	return out
}
开发者ID:xiaokangwang,项目名称:govpn,代码行数:36,代码来源:cnw.go

示例2: Winnow

// Winnow the data.
func Winnow(authKey *[32]byte, noncePrfx, in []byte) ([]byte, error) {
	if len(in)%EnlargeFactor != 0 {
		return nil, errors.New("Invalid data size")
	}
	out := make([]byte, len(in)/EnlargeFactor)
	keys := make([]byte, 8*64)
	nonce := make([]byte, 24)
	copy(nonce[:8], noncePrfx)
	var i int
	var v byte
	tag := new([16]byte)
	macKey := new([32]byte)
	defer zero(macKey[:])
	var is01 bool
	var is00 bool
	var is11 bool
	var is10 bool
	for n := 0; n < len(out); n++ {
		binary.BigEndian.PutUint64(nonce[16:], uint64(n))
		salsa20.XORKeyStream(keys, keys, nonce, authKey)
		v = 0
		for i = 0; i < 8; i++ {
			copy(macKey[:], keys[64*i:64*i+32])
			poly1305.Sum(tag, []byte("1"), macKey)
			is01 = subtle.ConstantTimeCompare(
				tag[:],
				in[16*(n*16+i*2):16*(n*16+i*2+1)],
			) == 1
			poly1305.Sum(tag, []byte("0"), macKey)
			is00 = subtle.ConstantTimeCompare(
				tag[:],
				in[16*(n*16+i*2):16*(n*16+i*2+1)],
			) == 1
			copy(macKey[:], keys[64*i+32:64*i+64])
			poly1305.Sum(tag, []byte("1"), macKey)
			is11 = subtle.ConstantTimeCompare(
				tag[:],
				in[16*(n*16+i*2+1):16*(n*16+i*2+2)],
			) == 1
			poly1305.Sum(tag, []byte("0"), macKey)
			is10 = subtle.ConstantTimeCompare(
				tag[:],
				in[16*(n*16+i*2+1):16*(n*16+i*2+2)],
			) == 1
			if !((is01 && is10) || (is00 && is11)) {
				zero(keys)
				return nil, errors.New("Invalid authenticator received")
			}
			if is11 {
				v = v | 1<<uint8(i)
			}
		}
		out[n] = v
		zero(keys)
	}
	return out, nil
}
开发者ID:xiaokangwang,项目名称:govpn,代码行数:58,代码来源:cnw.go

示例3: ResetPassword

func (sec *AccountSecurity) ResetPassword(kms security.KMS, password string) (*AccountSecurity, error) {
	kek := sec.SystemKey.Clone()
	if err := kms.DecryptKey(&kek); err != nil {
		return nil, fmt.Errorf("key decryption error: %s", err)
	}
	kek.IV = make([]byte, ClientKeyType.BlockSize())
	copy(kek.IV, sec.Nonce)

	clientKey := security.KeyFromPasscode([]byte(password), sec.Nonce, sec.UserKey.KeyType)
	if err := kek.Encrypt(clientKey); err != nil {
		return nil, fmt.Errorf("key encryption error: %s", err)
	}

	var (
		mac [16]byte
		key [32]byte
	)
	copy(key[:], clientKey.Plaintext)
	poly1305.Sum(&mac, sec.Nonce, &key)

	nsec := &AccountSecurity{
		Nonce:     sec.Nonce,
		MAC:       mac[:],
		SystemKey: sec.SystemKey,
		UserKey:   kek,
		KeyPair:   sec.KeyPair,
	}
	return nsec, nil
}
开发者ID:NotAMoose,项目名称:heim,代码行数:29,代码来源:account.go

示例4: ChangeClientKey

func (sec *AccountSecurity) ChangeClientKey(oldKey, newKey *security.ManagedKey) error {
	if oldKey.Encrypted() || newKey.Encrypted() {
		return security.ErrKeyMustBeDecrypted
	}

	// Extract decrypted UserKey and verify correctness of oldKey.
	kek, _, err := sec.unlock(oldKey)
	if err != nil {
		return err
	}

	// Encrypt new UserKey.
	if err := kek.Encrypt(newKey); err != nil {
		return err
	}

	// Update MAC and encrypted UserKey.
	var (
		mac [16]byte
		key [32]byte
	)
	copy(key[:], newKey.Plaintext)
	poly1305.Sum(&mac, sec.Nonce, &key)
	sec.MAC = mac[:]
	sec.UserKey = *kek

	return nil
}
开发者ID:NotAMoose,项目名称:heim,代码行数:28,代码来源:account.go

示例5: NewAgent

func NewAgent(agentID []byte, accessKey *security.ManagedKey) (*Agent, error) {
	if accessKey.Encrypted() {
		return nil, security.ErrKeyMustBeDecrypted
	}

	iv := make([]byte, accessKey.KeySize())
	if _, err := rand.Read(iv); err != nil {
		return nil, err
	}

	if agentID == nil {
		agentID = make([]byte, AgentIDSize)
		if _, err := rand.Read(agentID); err != nil {
			return nil, err
		}
	}

	var (
		mac [16]byte
		key [32]byte
	)
	copy(key[:], accessKey.Plaintext)
	poly1305.Sum(&mac, iv, &key)

	agent := &Agent{
		ID:      agentID,
		IV:      iv,
		MAC:     mac[:],
		Created: time.Now(),
	}
	return agent, nil
}
开发者ID:logan,项目名称:heim,代码行数:32,代码来源:agent.go

示例6: NewPM

func NewPM(kms security.KMS, client *Client, initiatorNick string, receiver UserID, receiverNick string) (
	*PM, *security.ManagedKey, error) {

	if client.Account == nil {
		return nil, nil, ErrAccessDenied
	}

	pmID, err := snowflake.New()
	if err != nil {
		return nil, nil, err
	}

	iv, err := kms.GenerateNonce(RoomMessageKeyType.BlockSize())
	if err != nil {
		return nil, nil, err
	}

	encryptedSystemKey, err := kms.GenerateEncryptedKey(RoomMessageKeyType, "pm", pmID.String())
	if err != nil {
		return nil, nil, err
	}

	pmKey := encryptedSystemKey.Clone()
	if err := kms.DecryptKey(&pmKey); err != nil {
		return nil, nil, fmt.Errorf("pm key decrypt: %s", err)
	}
	//pmKey.IV = iv

	userKey := client.Account.UserKey()
	if err := userKey.Decrypt(client.Authorization.ClientKey); err != nil {
		return nil, nil, fmt.Errorf("initiator account key decrypt: %s", err)
	}

	encryptedInitiatorKey := pmKey.Clone()
	encryptedInitiatorKey.IV = iv
	if err := encryptedInitiatorKey.Encrypt(&userKey); err != nil {
		return nil, nil, fmt.Errorf("initiator pm key encrypt: %s", err)
	}

	var (
		mac [16]byte
		key [32]byte
	)
	copy(key[:], pmKey.Plaintext)
	poly1305.Sum(&mac, []byte(receiver), &key)

	pm := &PM{
		ID:                    pmID,
		Initiator:             client.Account.ID(),
		InitiatorNick:         initiatorNick,
		Receiver:              receiver,
		ReceiverNick:          receiverNick,
		ReceiverMAC:           mac[:],
		IV:                    iv,
		EncryptedSystemKey:    encryptedSystemKey,
		EncryptedInitiatorKey: &encryptedInitiatorKey,
	}
	return pm, &pmKey, nil
}
开发者ID:logan,项目名称:heim,代码行数:59,代码来源:pm.go

示例7: poly1305MAC

func poly1305MAC(msg []byte, nonce []byte, key *MACKey) []byte {
	k := poly1305PrepareKey(nonce, key)

	var out [16]byte
	poly1305.Sum(&out, msg, &k)

	return out[:]
}
开发者ID:marete,项目名称:restic,代码行数:8,代码来源:crypto.go

示例8: handleRequest

func handleRequest(conn net.Conn) {
	timeCookie := tool.GetTimeCookie()
	initKey := sha256.Sum256([]byte(passwd + timeCookie))
	nonce := sha512.Sum512([]byte(timeCookie + passwd))

	es, err := chacha20.NewXChaCha(initKey[:], nonce[:XNonceSize])
	ds, err := chacha20.NewXChaCha(initKey[:], nonce[:XNonceSize])
	if err != nil {
		log.Println("Error chacha20 init:  ", err)
		return
	}

	pconn, err := net.Dial("tcp", server+":"+strconv.Itoa(sport))
	if err != nil {
		log.Println("Create connection failed :", err)
		return
	}
	cconn := cipherConn.NewCipherConn(ds, es, pconn)
	defer cconn.Close()

	randomDataLen, _ := tool.ReadInt(initKey[len(initKey)-2:])
	if randomDataLen < 32767 {
		randomDataLen = randomDataLen + 2984
	}

	randomData := make([]byte, randomDataLen+poly1305.TagSize)
	randbytes.Read(randomData)

	var mac [poly1305.TagSize]byte
	poly1305.Sum(&mac, randomData[:randomDataLen], &initKey)
	copy(randomData[randomDataLen:], mac[:])

	// Start proxying
	finish := make(chan bool, 4)

	// write random data head
	_, err = cconn.Write(randomData)
	if err != nil {
		log.Println("Connection write failed :", err)
		return
	}

	go proxy(cconn, conn, finish)
	go proxy(conn, cconn, finish)

	// Wait
	select {
	case <-finish:
	}

	time.Sleep(2 * time.Second)
}
开发者ID:Randomsock5,项目名称:Randomsocks5,代码行数:52,代码来源:rs-client.go

示例9: main

func main() {
	fmt.Println("[")

	// 5 tests
	for i := 0; i < 5; i++ {
		plaintext := make([]byte, 64)
		rand.Read(plaintext)

		key := make([]byte, 32)
		rand.Read(key)

		nonce := make([]byte, 8)
		rand.Read(nonce)

		stream, _ := chacha20.New(key[:], nonce)

		e32a := make([]byte, 32)
		var pkey [32]byte
		stream.XORKeyStream(pkey[:], e32a)

		ciphertext := make([]byte, 64)
		stream.XORKeyStream(ciphertext, plaintext)

		var tag [16]byte
		poly1305.Sum(&tag, ciphertext, &pkey)

		fmt.Printf(`	{
		key: new Buffer([
%s		]),
		nonce: new Buffer([
%s		]),
		plain: new Buffer([
%s		]),
		cipher: new Buffer([
%s		]),
		tag: new Buffer([
%s		]),
	},
`,
			hexify(key, "\t\t\t"),
			hexify(nonce, "\t\t\t"),
			hexify(plaintext, "\t\t\t"),
			hexify(ciphertext, "\t\t\t"),
			hexify(tag[:], "\t\t\t"),
		)
	}

	fmt.Println("]")
}
开发者ID:pgpst,项目名称:dancer,代码行数:49,代码来源:generate_tests.go

示例10: upgradeToAccountReceiver

func (pm *PM) upgradeToAccountReceiver(ctx scope.Context, b Backend, kms security.KMS, client *Client) (*security.ManagedKey, error) {
	// Verify that client and receiver agent share the same account.
	_, id := pm.Receiver.Parse()
	agent, err := b.AgentTracker().Get(ctx, id)
	if err != nil {
		return nil, err
	}
	if agent.AccountID != client.Account.ID().String() {
		return nil, ErrAccessDenied
	}

	// Unlock PM and verify Receiver.
	pmKey := pm.EncryptedSystemKey.Clone()
	if err := kms.DecryptKey(&pmKey); err != nil {
		return nil, err
	}
	if err := pm.verifyKey(&pmKey); err != nil {
		return nil, err
	}

	// Re-encrypt PM key for account.
	pm.Receiver = UserID(fmt.Sprintf("account:%s", client.Account.ID()))
	var (
		mac [16]byte
		key [32]byte
	)
	copy(key[:], pmKey.Plaintext)
	poly1305.Sum(&mac, []byte(pm.Receiver), &key)
	pm.ReceiverMAC = mac[:]

	userKey := client.Account.UserKey()
	if err := userKey.Decrypt(client.Authorization.ClientKey); err != nil {
		return nil, err
	}

	encryptedReceiverKey := pmKey.Clone()
	encryptedReceiverKey.IV = pm.IV
	if err := encryptedReceiverKey.Encrypt(&userKey); err != nil {
		return nil, err
	}
	pm.EncryptedReceiverKey = &encryptedReceiverKey

	if err := pm.verifyKey(&pmKey); err != nil {
		return nil, err
	}

	return &pmKey, nil
}
开发者ID:logan,项目名称:heim,代码行数:48,代码来源:pm.go

示例11: EthProcess

// Process incoming Ethernet packet.
// ready channel is TAPListen's synchronization channel used to tell him
// that he is free to receive new packets. Encrypted and authenticated
// packets will be sent to remote Peer side immediately.
func (p *Peer) EthProcess(data []byte, ready chan struct{}) {
	p.now = time.Now()
	p.size = len(data)
	// If this heartbeat is necessary
	if p.size == 0 && !p.LastSent.Add(p.Timeout).Before(p.now) {
		return
	}
	copy(p.buf, Emptiness)
	if p.size > 0 {
		copy(p.buf[S20BS+PktSizeSize:], data)
		ready <- struct{}{}
		binary.PutUvarint(p.buf[S20BS:S20BS+PktSizeSize], uint64(p.size))
		p.BytesPayloadOut += int64(p.size)
	} else {
		p.HeartbeatSent++
	}

	p.NonceOur += 2
	copy(p.nonce, Emptiness)
	binary.PutUvarint(p.nonce, p.NonceOur)
	p.NonceCipher.Encrypt(p.nonce, p.nonce)

	salsa20.XORKeyStream(p.buf, p.buf, p.nonce, p.Key)
	copy(p.buf[S20BS-NonceSize:S20BS], p.nonce)
	copy(p.keyAuth[:], p.buf[:SSize])
	if p.NoiseEnable {
		p.frame = p.buf[S20BS-NonceSize : S20BS+MTU-NonceSize-poly1305.TagSize]
	} else {
		p.frame = p.buf[S20BS-NonceSize : S20BS+PktSizeSize+p.size]
	}
	poly1305.Sum(p.tag, p.frame, p.keyAuth)

	p.BytesOut += int64(len(p.frame) + poly1305.TagSize)
	p.FramesOut++

	if p.CPRCycle != time.Duration(0) {
		p.willSentCycle = p.LastSent.Add(p.CPRCycle)
		if p.willSentCycle.After(p.now) {
			time.Sleep(p.willSentCycle.Sub(p.now))
			p.now = p.willSentCycle
		}
	}
	p.LastSent = p.now
	p.Conn.Write(append(p.frame, p.tag[:]...))
}
开发者ID:kenjoe41,项目名称:govpn,代码行数:49,代码来源:transport.go

示例12: DecryptAndVerify

// DecryptAndVerify returns the chacha20 decrypted messages.
// An error is returned when the poly1305 message authenticator (seal) could not be verified.
// Nonce should be 8 byte.
func DecryptAndVerify(key, nonce, message []byte, mac [16]byte, add []byte) ([]byte, error) {

	chacha20, err := chacha20.New(key, nonce)
	if err != nil {
		panic(err)
	}

	// poly1305 key is chacha20 over 32 zeros
	var poly1305Key [32]byte
	var chacha20KeyOut = make([]byte, 64)
	var zeros = make([]byte, 64)
	chacha20.XORKeyStream(chacha20KeyOut, zeros)
	copy(poly1305Key[:], chacha20KeyOut)

	var chacha20Out = make([]byte, len(message))
	var poly1305Out [16]byte

	// poly1305 byte order
	// - add bytes up to mod 16 (if available)
	// - message up to mod 16
	// - number of add bytes up to mod 8
	// - number of message bytes up to mod 8
	var poly1305In []byte
	if len(add) > 0 {
		poly1305In = AddBytes(poly1305In, add, 16)
	}

	poly1305In = AddBytes(poly1305In, message, 16)
	addLength := make([]byte, 8)
	msgLength := make([]byte, 8)
	binary.LittleEndian.PutUint64(addLength, uint64(len(add)))
	binary.LittleEndian.PutUint64(msgLength, uint64(len(message)))

	poly1305In = AddBytes(poly1305In, addLength, 8)
	poly1305In = AddBytes(poly1305In, msgLength, 8)

	poly1305.Sum(&poly1305Out, poly1305In, &poly1305Key)

	if poly1305.Verify(&mac, poly1305In, &poly1305Key) == false {
		return nil, errors.New("MAC not equal: " + hex.EncodeToString(poly1305Out[:]) + " != " + hex.EncodeToString(mac[:]))
	}

	chacha20.XORKeyStream(chacha20Out, message)
	return chacha20Out, nil
}
开发者ID:smitterson,项目名称:hc,代码行数:48,代码来源:chacha20_poly1305.go

示例13: Seal

// Seal appends an encrypted and authenticated copy of message to out, which
// must not overlap message. The key and nonce pair must be unique for each
// distinct message and the output will be Overhead bytes longer than message.
func Seal(out, message []byte, nonce *[24]byte, key *[32]byte) []byte {
	var subKey [32]byte
	var counter [16]byte
	setup(&subKey, &counter, nonce, key)

	// The Poly1305 key is generated by encrypting 32 bytes of zeros. Since
	// Salsa20 works with 64-byte blocks, we also generate 32 bytes of
	// keystream as a side effect.
	var firstBlock [64]byte
	salsa.XORKeyStream(firstBlock[:], firstBlock[:], &counter, &subKey)

	var poly1305Key [32]byte
	copy(poly1305Key[:], firstBlock[:])

	ret, out := sliceForAppend(out, len(message)+poly1305.TagSize)

	// We XOR up to 32 bytes of message with the keystream generated from
	// the first block.
	firstMessageBlock := message
	if len(firstMessageBlock) > 32 {
		firstMessageBlock = firstMessageBlock[:32]
	}

	tagOut := out
	out = out[poly1305.TagSize:]
	for i, x := range firstMessageBlock {
		out[i] = firstBlock[32+i] ^ x
	}
	message = message[len(firstMessageBlock):]
	ciphertext := out
	out = out[len(firstMessageBlock):]

	// Now encrypt the rest.
	counter[8] = 1
	salsa.XORKeyStream(out, message, &counter, &subKey)

	var tag [poly1305.TagSize]byte
	poly1305.Sum(&tag, ciphertext, &poly1305Key)
	copy(tagOut, tag[:])

	return ret
}
开发者ID:Rudloff,项目名称:platform,代码行数:45,代码来源:secretbox.go

示例14: sealGeneric

func (c *chacha20poly1305) sealGeneric(dst, nonce, plaintext, additionalData []byte) []byte {
	var counter [16]byte
	copy(counter[4:], nonce)

	var polyKey [32]byte
	chacha20.XORKeyStream(polyKey[:], polyKey[:], &counter, &c.key)

	ret, out := sliceForAppend(dst, len(plaintext)+poly1305.TagSize)
	counter[0] = 1
	chacha20.XORKeyStream(out, plaintext, &counter, &c.key)

	polyInput := make([]byte, roundTo16(len(additionalData))+roundTo16(len(plaintext))+8+8)
	copy(polyInput, additionalData)
	copy(polyInput[roundTo16(len(additionalData)):], out[:len(plaintext)])
	binary.LittleEndian.PutUint64(polyInput[len(polyInput)-16:], uint64(len(additionalData)))
	binary.LittleEndian.PutUint64(polyInput[len(polyInput)-8:], uint64(len(plaintext)))

	var tag [poly1305.TagSize]byte
	poly1305.Sum(&tag, polyInput, &polyKey)
	copy(out[len(plaintext):], tag[:])

	return ret
}
开发者ID:40a,项目名称:ejson,代码行数:23,代码来源:chacha20poly1305_generic.go

示例15: EncryptAndSeal

// EncryptAndSeal returns the chacha20 encrypted message and poly1305 message authentictor (also refered as seals)
// Nonce should be 8 byte
func EncryptAndSeal(key, nonce, message []byte, add []byte) ([]byte /*encrypted*/, [16]byte /*mac*/, error) {

	chacha20, err := chacha20.New(key, nonce)
	if err != nil {
		panic(err)
	}

	// poly1305 key is chacha20 over 32 zeros
	var poly1305Key [32]byte
	var chacha20KeyOut = make([]byte, 64)
	var zeros = make([]byte, 64)
	chacha20.XORKeyStream(chacha20KeyOut, zeros)
	copy(poly1305Key[:], chacha20KeyOut)

	var chacha20Out = make([]byte, len(message))
	var poly1305Out [16]byte
	chacha20.XORKeyStream(chacha20Out, message)

	var poly1305In []byte
	if len(add) > 0 {
		poly1305In = AddBytes(poly1305In, add, 16)
	}

	poly1305In = AddBytes(poly1305In, chacha20Out, 16)
	addLength := make([]byte, 8)
	msgLength := make([]byte, 8)
	binary.LittleEndian.PutUint64(addLength, uint64(len(add)))
	binary.LittleEndian.PutUint64(msgLength, uint64(len(message)))

	poly1305In = AddBytes(poly1305In, addLength, 8)
	poly1305In = AddBytes(poly1305In, msgLength, 8)

	poly1305.Sum(&poly1305Out, poly1305In, &poly1305Key)

	return chacha20Out, poly1305Out, nil
}
开发者ID:smitterson,项目名称:hc,代码行数:38,代码来源:chacha20_poly1305.go


注:本文中的golang.org/x/crypto/poly1305.Sum函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。