You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.example.utils
import kotlin.math.pow
sealed interface Encryptable {
val data: ByteArray
val type:Int
data class Encrypt( override val data: ByteArray, override val type: Int = 1
): Encryptable {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Encrypt
if (type != other.type) return false
if (!data.contentEquals(other.data)) return false
return true
}
override fun hashCode(): Int {
var result = type
result = 31 * result + data.contentHashCode()
return result
}
}
data class Decrypt(override val data: ByteArray, override val type:Int = -1): Encryptable {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Decrypt
if (type != other.type) return false
if (!data.contentEquals(other.data)) return false
return true
}
override fun hashCode(): Int {
var result = type
result = 31 * result + data.contentHashCode()
return result
}
}
}
private fun Byte.encryption(key: Byte, method: Int): Byte {
// key的预处理处理结果0<=key&&key<8
val msg = this
var key = key
key = (method * (key % 8)).toByte()
key = (if (key >= 0) key else key + 8).toByte()
// msg的预处理避免msg首位为1
var nMsg = msg.toInt() and 255
// 移位掩码tmp保存低位溢出信息
val mask = 2.0.pow(key.toDouble()).toInt() - 1
var tmp = nMsg and mask
// 循环移位
nMsg = nMsg shr key.toInt()
tmp = tmp shl 8 - key // 低位溢出信息移至高位
nMsg = nMsg or tmp
return (255 and nMsg).toByte() // 取出低8位
}
fun ByteArray.encryption(encryptable: Encryptable): ByteArray {
val result = ByteArray(encryptable.data.size)
encryptable.data.forEachIndexed { index, byte ->
result[index] = byte.encryption(this[index % size], encryptable.type)
}
return result
}