@ -7,8 +7,17 @@ private const val ROUNDS = 32
private const val BLOCK _SIZE = 8
private const val BLOCK _SIZE = 8
private const val BLOCK _SIZE _MASK = BLOCK _SIZE - 1
private const val BLOCK _SIZE _MASK = BLOCK _SIZE - 1
fun ByteBuf . xteaEncrypt ( index : Int , length : Int , key : IntArray ) {
inline class XteaKey ( internal val k : IntArray ) {
require ( key . size == 4 )
val isZero : Boolean
get ( ) = k [ 0 ] == 0 && k [ 1 ] == 0 && k [ 2 ] == 0 && k [ 3 ] == 0
companion object {
val ZERO = XteaKey ( IntArray ( 4 ) )
}
}
fun ByteBuf . xteaEncrypt ( index : Int , length : Int , key : XteaKey ) {
require ( key . k . size == 4 )
val end = index + ( length and BLOCK _SIZE _MASK . inv ( ) )
val end = index + ( length and BLOCK _SIZE _MASK . inv ( ) )
for ( i in index until end step BLOCK _SIZE ) {
for ( i in index until end step BLOCK _SIZE ) {
@ -17,9 +26,9 @@ fun ByteBuf.xteaEncrypt(index: Int, length: Int, key: IntArray) {
var v1 = getInt ( i + 4 )
var v1 = getInt ( i + 4 )
for ( j in 0 until ROUNDS ) {
for ( j in 0 until ROUNDS ) {
v0 += ( ( ( v1 shl 4 ) xor ( v1 ushr 5 ) ) + v1 ) xor ( sum + key [ sum and 3 ] )
v0 += ( ( ( v1 shl 4 ) xor ( v1 ushr 5 ) ) + v1 ) xor ( sum + key . k [ sum and 3 ] )
sum += GOLDEN _RATIO
sum += GOLDEN _RATIO
v1 += ( ( ( v0 shl 4 ) xor ( v0 ushr 5 ) ) + v0 ) xor ( sum + key [ ( sum ushr 11 ) and 3 ] )
v1 += ( ( ( v0 shl 4 ) xor ( v0 ushr 5 ) ) + v0 ) xor ( sum + key . k [ ( sum ushr 11 ) and 3 ] )
}
}
setInt ( i , v0 )
setInt ( i , v0 )
@ -27,8 +36,8 @@ fun ByteBuf.xteaEncrypt(index: Int, length: Int, key: IntArray) {
}
}
}
}
fun ByteBuf . xteaDecrypt ( index : Int , length : Int , key : IntArra y) {
fun ByteBuf . xteaDecrypt ( index : Int , length : Int , key : XteaKe y) {
require ( key . size == 4 )
require ( key . k . size == 4 )
val end = index + ( length and BLOCK _SIZE _MASK . inv ( ) )
val end = index + ( length and BLOCK _SIZE _MASK . inv ( ) )
for ( i in index until end step BLOCK _SIZE ) {
for ( i in index until end step BLOCK _SIZE ) {
@ -38,9 +47,9 @@ fun ByteBuf.xteaDecrypt(index: Int, length: Int, key: IntArray) {
var v1 = getInt ( i + 4 )
var v1 = getInt ( i + 4 )
for ( j in 0 until ROUNDS ) {
for ( j in 0 until ROUNDS ) {
v1 -= ( ( ( v0 shl 4 ) xor ( v0 ushr 5 ) ) + v0 ) xor ( sum + key [ ( sum ushr 11 ) and 3 ] )
v1 -= ( ( ( v0 shl 4 ) xor ( v0 ushr 5 ) ) + v0 ) xor ( sum + key . k [ ( sum ushr 11 ) and 3 ] )
sum -= GOLDEN _RATIO
sum -= GOLDEN _RATIO
v0 -= ( ( ( v1 shl 4 ) xor ( v1 ushr 5 ) ) + v1 ) xor ( sum + key [ sum and 3 ] )
v0 -= ( ( ( v1 shl 4 ) xor ( v1 ushr 5 ) ) + v1 ) xor ( sum + key . k [ sum and 3 ] )
}
}
setInt ( i , v0 )
setInt ( i , v0 )