您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

88 行
2.2 KiB

  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build go1.7,amd64,!gccgo,!appengine
  5. package chacha20poly1305
  6. import (
  7. "encoding/binary"
  8. "golang.org/x/crypto/internal/subtle"
  9. "golang.org/x/sys/cpu"
  10. )
  11. //go:noescape
  12. func chacha20Poly1305Open(dst []byte, key []uint32, src, ad []byte) bool
  13. //go:noescape
  14. func chacha20Poly1305Seal(dst []byte, key []uint32, src, ad []byte)
  15. var (
  16. useASM = cpu.X86.HasSSSE3
  17. useAVX2 = cpu.X86.HasAVX2 && cpu.X86.HasBMI2
  18. )
  19. // setupState writes a ChaCha20 input matrix to state. See
  20. // https://tools.ietf.org/html/rfc7539#section-2.3.
  21. func setupState(state *[16]uint32, key *[8]uint32, nonce []byte) {
  22. state[0] = 0x61707865
  23. state[1] = 0x3320646e
  24. state[2] = 0x79622d32
  25. state[3] = 0x6b206574
  26. state[4] = key[0]
  27. state[5] = key[1]
  28. state[6] = key[2]
  29. state[7] = key[3]
  30. state[8] = key[4]
  31. state[9] = key[5]
  32. state[10] = key[6]
  33. state[11] = key[7]
  34. state[12] = 0
  35. state[13] = binary.LittleEndian.Uint32(nonce[:4])
  36. state[14] = binary.LittleEndian.Uint32(nonce[4:8])
  37. state[15] = binary.LittleEndian.Uint32(nonce[8:12])
  38. }
  39. func (c *chacha20poly1305) seal(dst, nonce, plaintext, additionalData []byte) []byte {
  40. if !useASM {
  41. return c.sealGeneric(dst, nonce, plaintext, additionalData)
  42. }
  43. var state [16]uint32
  44. setupState(&state, &c.key, nonce)
  45. ret, out := sliceForAppend(dst, len(plaintext)+16)
  46. if subtle.InexactOverlap(out, plaintext) {
  47. panic("chacha20poly1305: invalid buffer overlap")
  48. }
  49. chacha20Poly1305Seal(out[:], state[:], plaintext, additionalData)
  50. return ret
  51. }
  52. func (c *chacha20poly1305) open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
  53. if !useASM {
  54. return c.openGeneric(dst, nonce, ciphertext, additionalData)
  55. }
  56. var state [16]uint32
  57. setupState(&state, &c.key, nonce)
  58. ciphertext = ciphertext[:len(ciphertext)-16]
  59. ret, out := sliceForAppend(dst, len(ciphertext))
  60. if subtle.InexactOverlap(out, ciphertext) {
  61. panic("chacha20poly1305: invalid buffer overlap")
  62. }
  63. if !chacha20Poly1305Open(out, state[:], ciphertext, additionalData) {
  64. for i := range out {
  65. out[i] = 0
  66. }
  67. return nil, errOpen
  68. }
  69. return ret, nil
  70. }