上面的是TEA的算法,XTEA的算法为:
#include <stdint.h>
void encipher(unsigned int num_rounds, uint32_t v[2], uint32_t const k[4]) { unsigned int i; uint32_t v0=v[0], v1=v[1], sum=0, delta=0x9E3779B9; for (i=0; i < num_rounds; i++) { v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]); sum += delta; v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]); } v[0]=v0; v[1]=v1; }
void decipher(unsigned int num_rounds, uint32_t v[2], uint32_t const k[4]) { unsigned int i; uint32_t v0=v[0], v1=v[1], delta=0x9E3779B9, sum=delta*num_rounds; for (i=0; i < num_rounds; i++) { v1 −= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]); sum −= delta; v0 −= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]); } v[0]=v0; v[1]=v1; }
那PHP中只需要把运算的位置改下就OK
private function _teaencipherLong($y, $z, &$w, &$k) { $sum = ( integer ) 0; $delta = 0x9E3779B9; $n = ( integer ) $this->n_iter; while ( $n -- > 0 ) { $y = $this->_add ( $y, $this->_add ( $z << 4 ^ $this->_rshift ( $z, 5 ), $z ) ^ $this->_add ( $sum, $k [$sum & 3] ) ); $sum = $this->_add ( $sum, $delta ); $z = $this->_add ( $z, $this->_add ( $y << 4 ^ $this->_rshift ( $y, 5 ), $y ) ^ $this->_add ( $sum, $k [$this->_rshift ( $sum, 11 ) & 3] ) ); } $w [0] = $y; $w [1] = $z; } private function _decipherLong($y, $z, &$w, &$k) { // sum = delta<<5, in general sum = delta * n $sum = 0xC6EF3720; $delta = 0x9E3779B9; $n = ( integer ) $this->n_iter; while ( $n -- > 0 ) { $z = $this->_add ( $z, - ($this->_add ( $y << 4 ^ $this->_rshift ( $y, 5 ), $y ) ^ $this->_add ( $sum, $k [$this->_rshift ( $sum, 11 ) & 3] )) ); $sum = $this->_add ( $sum, - $delta ); $y = $this->_add ( $y, - ($this->_add ( $z << 4 ^ $this->_rshift ( $z, 5 ), $z ) ^ $this->_add ( $sum, $k [$sum & 3] )) ); } $w [0] = $y; $w [1] = $z; }
|