chacha_core_gen.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // +build generate
  2. package main
  3. import (
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. func writeQuarterRound(file *os.File, a, b, c, d int) {
  9. add := "x%d+=x%d\n"
  10. xor := "x=x%d^x%d\n"
  11. rotate := "x%d=(x << %d) | (x >> (32 - %d))\n"
  12. fmt.Fprintf(file, add, a, b)
  13. fmt.Fprintf(file, xor, d, a)
  14. fmt.Fprintf(file, rotate, d, 16, 16)
  15. fmt.Fprintf(file, add, c, d)
  16. fmt.Fprintf(file, xor, b, c)
  17. fmt.Fprintf(file, rotate, b, 12, 12)
  18. fmt.Fprintf(file, add, a, b)
  19. fmt.Fprintf(file, xor, d, a)
  20. fmt.Fprintf(file, rotate, d, 8, 8)
  21. fmt.Fprintf(file, add, c, d)
  22. fmt.Fprintf(file, xor, b, c)
  23. fmt.Fprintf(file, rotate, b, 7, 7)
  24. }
  25. func writeChacha20Block(file *os.File) {
  26. fmt.Fprintln(file, `
  27. func ChaCha20Block(s *[16]uint32, out []byte, rounds int) {
  28. var x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15 = s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8],s[9],s[10],s[11],s[12],s[13],s[14],s[15]
  29. for i := 0; i < rounds; i+=2 {
  30. var x uint32
  31. `)
  32. writeQuarterRound(file, 0, 4, 8, 12)
  33. writeQuarterRound(file, 1, 5, 9, 13)
  34. writeQuarterRound(file, 2, 6, 10, 14)
  35. writeQuarterRound(file, 3, 7, 11, 15)
  36. writeQuarterRound(file, 0, 5, 10, 15)
  37. writeQuarterRound(file, 1, 6, 11, 12)
  38. writeQuarterRound(file, 2, 7, 8, 13)
  39. writeQuarterRound(file, 3, 4, 9, 14)
  40. fmt.Fprintln(file, "}")
  41. for i := 0; i < 16; i++ {
  42. fmt.Fprintf(file, "binary.LittleEndian.PutUint32(out[%d:%d], s[%d]+x%d)\n", i*4, i*4+4, i, i)
  43. }
  44. fmt.Fprintln(file, "}")
  45. fmt.Fprintln(file)
  46. }
  47. func main() {
  48. file, err := os.OpenFile("chacha_core.generated.go", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
  49. if err != nil {
  50. log.Fatalf("Failed to generate chacha_core.go: %v", err)
  51. }
  52. defer file.Close()
  53. fmt.Fprintln(file, "package internal")
  54. fmt.Fprintln(file)
  55. fmt.Fprintln(file, "import \"encoding/binary\"")
  56. fmt.Fprintln(file)
  57. writeChacha20Block(file)
  58. }