github.com/EagleQL/Xray-core@v1.4.3/common/crypto/internal/chacha_core_gen.go (about) 1 // +build generate 2 3 package main 4 5 import ( 6 "fmt" 7 "log" 8 "os" 9 ) 10 11 func writeQuarterRound(file *os.File, a, b, c, d int) { 12 add := "x%d+=x%d\n" 13 xor := "x=x%d^x%d\n" 14 rotate := "x%d=(x << %d) | (x >> (32 - %d))\n" 15 16 fmt.Fprintf(file, add, a, b) 17 fmt.Fprintf(file, xor, d, a) 18 fmt.Fprintf(file, rotate, d, 16, 16) 19 20 fmt.Fprintf(file, add, c, d) 21 fmt.Fprintf(file, xor, b, c) 22 fmt.Fprintf(file, rotate, b, 12, 12) 23 24 fmt.Fprintf(file, add, a, b) 25 fmt.Fprintf(file, xor, d, a) 26 fmt.Fprintf(file, rotate, d, 8, 8) 27 28 fmt.Fprintf(file, add, c, d) 29 fmt.Fprintf(file, xor, b, c) 30 fmt.Fprintf(file, rotate, b, 7, 7) 31 } 32 33 func writeChacha20Block(file *os.File) { 34 fmt.Fprintln(file, ` 35 func ChaCha20Block(s *[16]uint32, out []byte, rounds int) { 36 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] 37 for i := 0; i < rounds; i+=2 { 38 var x uint32 39 `) 40 41 writeQuarterRound(file, 0, 4, 8, 12) 42 writeQuarterRound(file, 1, 5, 9, 13) 43 writeQuarterRound(file, 2, 6, 10, 14) 44 writeQuarterRound(file, 3, 7, 11, 15) 45 writeQuarterRound(file, 0, 5, 10, 15) 46 writeQuarterRound(file, 1, 6, 11, 12) 47 writeQuarterRound(file, 2, 7, 8, 13) 48 writeQuarterRound(file, 3, 4, 9, 14) 49 fmt.Fprintln(file, "}") 50 for i := 0; i < 16; i++ { 51 fmt.Fprintf(file, "binary.LittleEndian.PutUint32(out[%d:%d], s[%d]+x%d)\n", i*4, i*4+4, i, i) 52 } 53 fmt.Fprintln(file, "}") 54 fmt.Fprintln(file) 55 } 56 57 func main() { 58 file, err := os.OpenFile("chacha_core.generated.go", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) 59 if err != nil { 60 log.Fatalf("Failed to generate chacha_core.go: %v", err) 61 } 62 defer file.Close() 63 64 fmt.Fprintln(file, "package internal") 65 fmt.Fprintln(file) 66 fmt.Fprintln(file, "import \"encoding/binary\"") 67 fmt.Fprintln(file) 68 writeChacha20Block(file) 69 }