github.com/Asutorufa/yuhaiin@v0.3.6-0.20240502055049-7984da7023a0/pkg/net/proxy/shadowsocksr/utils/crc32.go (about)

     1  package ssr
     2  
     3  import (
     4  	"encoding/binary"
     5  )
     6  
     7  var (
     8  	crc32Table = make([]uint32, 256)
     9  )
    10  
    11  func init() {
    12  	createCRC32Table()
    13  }
    14  
    15  func createCRC32Table() {
    16  	for i := 0; i < 256; i++ {
    17  		crc := uint32(i)
    18  		for j := 8; j > 0; j-- {
    19  			if crc&1 == 1 {
    20  				crc = (crc >> 1) ^ 0xEDB88320
    21  			} else {
    22  				crc >>= 1
    23  			}
    24  		}
    25  		crc32Table[i] = crc
    26  	}
    27  }
    28  
    29  func CalcCRC32(input []byte, length int) uint32 {
    30  	return doCalcCRC32(input, length, 0xFFFFFFFF)
    31  }
    32  
    33  func doCalcCRC32(input []byte, length int, value uint32) uint32 {
    34  	buffer := input
    35  	for i := 0; i < length; i++ {
    36  		value = (value >> 8) ^ crc32Table[byte(value&0xFF)^buffer[i]]
    37  	}
    38  	return value ^ 0xFFFFFFFF
    39  }
    40  
    41  func SetCRC32(buffer []byte, length int) {
    42  	doSetCRC32(buffer, length)
    43  }
    44  
    45  func doSetCRC32(buffer []byte, length int) {
    46  	crc := CalcCRC32(buffer[:length-4], length-4)
    47  	binary.LittleEndian.PutUint32(buffer[length-4:], crc^0xFFFFFFFF)
    48  }