Skip to content

Instantly share code, notes, and snippets.

@vizee
Last active May 28, 2018 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vizee/330661ed2d27a41fc4832a17d45f8f3c to your computer and use it in GitHub Desktop.
Save vizee/330661ed2d27a41fc4832a17d45f8f3c to your computer and use it in GitHub Desktop.
xxtea
package xxtea
import (
"unsafe"
)
const _DELTA = 0x9e3779b9
func EncryptBytes(m []byte, k *[4]uint32) {
if len(m) < 8 {
return
}
vptr := uintptr(unsafe.Pointer(&m[0]))
n := uint32(len(m) / 4)
vlast := vptr + uintptr(n*4-4)
rounds := 6 + 52/n
sum := uint32(0)
z := *(*uint32)(unsafe.Pointer(vlast))
for {
sum += _DELTA
e := (sum >> 2) & 3
p := uint32(0)
for ; p < n-1; p++ {
v := (*[2]uint32)(unsafe.Pointer(vptr + uintptr(p*4)))
y := v[1]
v[0] += (((z>>5 ^ y<<2) + (y>>3 ^ z<<4)) ^ ((sum ^ y) + (k[((p&3)^e)&3] ^ z)))
z = v[0]
}
y := *(*uint32)(unsafe.Pointer(vptr))
*(*uint32)(unsafe.Pointer(vlast)) += (((z>>5 ^ y<<2) + (y>>3 ^ z<<4)) ^ ((sum ^ y) + (k[((p&3)^e)&3] ^ z)))
z = *(*uint32)(unsafe.Pointer(vlast))
rounds--
if rounds == 0 {
break
}
}
}
func DecryptBytes(m []byte, k *[4]uint32) {
if len(m) < 8 {
return
}
vptr := uintptr(unsafe.Pointer(&m[0]))
n := uint32(len(m) / 4)
vlast := vptr + uintptr(n*4-4)
rounds := 6 + 52/n
sum := uint32(rounds * _DELTA)
y := *(*uint32)(unsafe.Pointer(vptr))
var z uint32
for {
e := (sum >> 2) & 3
p := n - 1
for ; p > 0; p-- {
v := (*[2]uint32)(unsafe.Pointer(vptr + uintptr(p*4) - 4))
z = v[0]
v[1] -= (((z>>5 ^ y<<2) + (y>>3 ^ z<<4)) ^ ((sum ^ y) + (k[((p&3)^e)&3] ^ z)))
y = v[1]
}
z = *(*uint32)(unsafe.Pointer(vlast))
*(*uint32)(unsafe.Pointer(vptr)) -= (((z>>5 ^ y<<2) + (y>>3 ^ z<<4)) ^ ((sum ^ y) + (k[((p&3)^e)&3] ^ z)))
y = *(*uint32)(unsafe.Pointer(vptr))
sum -= _DELTA
rounds--
if rounds == 0 {
break
}
}
}
func Encrypt(v []uint32, k *[4]uint32) {
if len(v) <= 1 {
return
}
n := len(v)
rounds := 6 + 52/n
sum := uint32(0)
z := v[n-1]
for {
sum += _DELTA
e := (sum >> 2) & 3
p := 0
for ; p < n-1; p++ {
y := v[p+1]
v[p] += (((z>>5 ^ y<<2) + (y>>3 ^ z<<4)) ^ ((sum ^ y) + (k[uint32(p&3)^e] ^ z)))
z = v[p]
}
y := v[0]
v[n-1] += (((z>>5 ^ y<<2) + (y>>3 ^ z<<4)) ^ ((sum ^ y) + (k[uint32(p&3)^e] ^ z)))
z = v[n-1]
rounds--
if rounds == 0 {
break
}
}
}
func Decrypt(v []uint32, k *[4]uint32) {
if len(v) <= 1 {
return
}
n := len(v)
rounds := 6 + 52/n
sum := uint32(rounds * _DELTA)
y := v[0]
var z uint32
for {
e := (sum >> 2) & 3
p := n - 1
for ; p > 0; p-- {
z = v[p-1]
v[p] -= (((z>>5 ^ y<<2) + (y>>3 ^ z<<4)) ^ ((sum ^ y) + (k[uint32(p&3)^e] ^ z)))
y = v[p]
}
z = v[n-1]
v[0] -= (((z>>5 ^ y<<2) + (y>>3 ^ z<<4)) ^ ((sum ^ y) + (k[uint32(p&3)^e] ^ z)))
y = v[0]
sum -= _DELTA
rounds--
if rounds == 0 {
break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment