py版本
import base64
import math
import random
class Cys:
def exinst_matrix(self, matrixs: list, num: int, where: int):
for index, matrix in enumerate(matrixs):
if matrix[where] == num:
return index
return None
def str_to_matrix(self, s: str):
matrixs = []
for i, c in enumerate(s):
c = ord(c)
index = self.exinst_matrix(matrixs, c, 1)
if index is None:
index = random.randint(0, len(s) + 1000)
while self.exinst_matrix(matrixs, index, 0) is not None:
index = random.randint(0, len(s) + 1000)
matrixs.append([index, c, i])
else:
matrixs[index] += [i]
return matrixs
def sort_matrix(self, matrixs: list[list]):
matrixs = sorted(matrixs, key=lambda x: x[0])
return matrixs
def pop_real_code(self, matrixs: list[list]):
for matrix in matrixs:
matrix.pop(1)
return matrixs
def pop_random_index(self, matrixs: list[list]):
for matrix in matrixs:
matrix.pop(0)
return matrixs
def rows_move(self, matrixs: list[list], key: list, decode: bool):
if decode:
matrixs = sorted(matrixs, key=lambda x: x[0])
for index, matrix in enumerate(matrixs):
where = -1
if key[index] % 2:
where = 1
if decode:
matrix.pop(0)
matrix[0] += key[index] * where * 10
matrixs[index] = matrix
else:
matrix[0] -= key[index] * where * 10
matrix = [index] + matrix
matrixs[index] = matrix
if not decode:
matrixs = sorted(matrixs, key=lambda x: x[1])
return matrixs
def nodes_move(self, matrixs: list[list], key: list, decode: bool):
for index, matrix in enumerate(matrixs):
where = -1
if key[index] % 2:
where = 1
# 点移位
for index2, node in enumerate(matrix):
if decode:
node -= key[index] * where * 10
matrix[index2] = node
else:
node += key[index] * where * 10
matrix[index2] = node
matrixs[index] = matrix
return matrixs
def format_key(self, key: list, data: list):
temp = []
for i in key:
temp += i
key = temp
while len(key) < len(data):
key += key
return key
def is_int(self, s: str):
try:
int(s)
return True
except ValueError:
return False
def count_char(self, input_str, char_to_count):
return input_str.count(char_to_count)
def shift_string(self, strings, n):
shifted = "".join([chr(ord(s) + n) for s in strings])
return shifted
def decode(self, data: str, key: str):
key_len = len(key)
key_one_value = 0
for x in key:
key_one_value += ord(x)
data = base64.b64decode(data.encode()).decode()
move_step = math.floor(len(data) / 3) + key_len + key_one_value
while move_step > 100:
move_step -= 100
move_step *= -1
data = self.shift_string(data, move_step)
data = data.split("+==")
temp = []
for item in data:
if item == "":
continue
item.replace("*", "")
item.replace(" ", "")
item = item.encode()
item = base64.decodebytes(item)
item = item.decode()
item = item.split("=")
temp.append(item)
data = temp
data = list(map(lambda x: list(map(lambda y: int(y), x)), data))
index_list = data.pop()
data_index_list = index_list[0 : len(data)]
key_index_list = index_list[len(data) :]
key = self.str_to_matrix(key)
if len(key_index_list) != len(key):
raise ("key length error")
for index, k in enumerate(key):
key[index][0] = int(key_index_list[index])
key = self.sort_matrix(key)
key = self.pop_real_code(key)
key = self.format_key(key, data)
data = self.rows_move(data, key, True)
data = self.nodes_move(data, key, True)
if len(data_index_list) != len(data):
raise ("data length error")
s = ""
count = 0
str_length = 0
for x in data:
str_length += len(x) - 1
while len(s) < str_length:
for index, d in enumerate(data):
for index2, x in enumerate(d):
if index2 == 0:
continue
if x == count:
asccode = d[0]
s += chr(asccode)
count += 1
return s
def encode(self, data: str, key: str):
# 数据准备
key_len = len(key)
key_one_value = 0
for x in key:
key_one_value += ord(x)
data = self.str_to_matrix(data)
data_index_list = list(map(lambda x: x[0], data))
data = self.sort_matrix(data)
data = self.pop_random_index(data)
# data = self.pop_real_code(data)
key = self.str_to_matrix(key)
key_index_list = list(map(lambda x: x[0], key))
key = self.sort_matrix(key)
key = self.pop_real_code(key)
key = self.format_key(key, data)
index_list = data_index_list + key_index_list
# # 开始加密
# # 移位
data = self.nodes_move(data, key, False)
data = self.rows_move(data, key, False)
data.append(index_list)
# # 结束加密
temp = []
for item in data:
item = "=".join(list(map(lambda y: str(y), item))).encode()
item = base64.encodebytes(item)
item = item.decode()
item = item.replace("\n", "")
temp.append(item)
data = "+==".join(temp)
move_step = math.floor(len(data) / 3) + key_len + key_one_value
while move_step > 100:
move_step -= 100
data = self.shift_string(data, move_step)
data = base64.b64encode(data.encode()).decode()
return data
encodeData = Cys().encode("你好", "asdasdasdawdawkjmnl;'kr")
print(encodeData)
decodeData = Cys().decode(encodeData, "asdasdasdawdawkjmnl;'kr")
print(decodeData)
js版本
class Cys {
shiftString(strings, n) {
const shifted = strings.split("").map(s => String.fromCharCode(s.charCodeAt(0) + n)).join("");
return shifted;
}
exinstMatrix(matrixs, num, where) {
for (let index = 0; index < matrixs.length; index++) {
if (matrixs[index][where] === num) {
return index;
}
}
return null;
}
strToMatrix(s) {
const matrixs = [];
for (let i = 0; i < s.length; i++) {
const c = s.charCodeAt(i);
let index = this.exinstMatrix(matrixs, c, 1);
if (index === null) {
index = Math.floor(Math.random() * (s.length + 1000));
while (this.exinstMatrix(matrixs, index, 0) !== null) {
index = Math.floor(Math.random() * (s.length + 1000));
}
matrixs.push([index, c, i]);
} else {
matrixs[index].push(i);
}
}
return matrixs;
}
sortMatrix(matrixs) {
return matrixs.sort((a, b) => a[0] - b[0]);
}
popRealCode(matrixs) {
for (let matrix of matrixs) {
matrix.splice(1, 1);
}
return matrixs;
}
popRandomIndex(matrixs) {
for (let matrix of matrixs) {
matrix.splice(0, 1);
}
return matrixs;
}
rowsMove(matrixs, key, decode) {
if (decode) {
matrixs = this.sortMatrix(matrixs);
}
for (let index = 0; index < matrixs.length; index++) {
let where = -1;
if (key[index] % 2) {
where = 1;
}
if (decode) {
matrixs[index].splice(0, 1);
matrixs[index][0] += key[index] * where * 10;
} else {
matrixs[index][0] -= key[index] * where * 10;
matrixs[index] = [index].concat(matrixs[index]);
}
}
if (!decode) {
matrixs = this.sortMatrix(matrixs);
}
return matrixs;
}
nodesMove(matrixs, key, decode) {
for (let index = 0; index < matrixs.length; index++) {
let where = -1;
if (key[index] % 2) {
where = 1;
}
for (let index2 = 0; index2 < matrixs[index].length; index2++) {
if (decode) {
matrixs[index][index2] -= key[index] * where * 10;
} else {
matrixs[index][index2] += key[index] * where * 10;
}
}
}
return matrixs;
}
formatKey(key, data) {
const temp = [];
for (let i of key) {
temp.push(...i);
}
key = temp;
while (key.length < data.length) {
key.push(...key);
}
return key;
}
isInt(s) {
return !isNaN(s) && !isNaN(parseFloat(s));
}
countChar(inputStr, charToCount) {
return inputStr.split(charToCount).length - 1;
}
decode(data, key) {
const keyLen = key.length
let keyOnevalue = 0
for (let i in key){
keyOnevalue += key.charCodeAt(i)
}
data = Buffer.from(data, 'base64');
data = new TextDecoder().decode(data);
let move_step = Math.floor(data.split("").length / 3) + keyLen + keyOnevalue
while (move_step > 100){
move_step -= 100
}
move_step *= -1
data = this.shiftString(data, move_step)
data = data.split("+==");
const temp = [];
for (let item of data) {
if (item === "") {
continue;
}
item = item.replace(/\*/g, "").replace(/\s/g, "");
item = Buffer.from(item, 'base64');
item = new TextDecoder().decode(item);
item = item.split("=");
temp.push(item);
}
data = temp;
data = data.map(x => x.map(y => parseInt(y)));
const indexList = data.pop();
const dataIndexList = indexList.slice(0, data.length);
const keyIndexList = indexList.slice(data.length);
key = this.strToMatrix(key);
if (keyIndexList.length !== key.length) {
throw new Error("key length error");
}
for (let index = 0; index < key.length; index++) {
key[index][0] = parseInt(keyIndexList[index]);
}
key = this.sortMatrix(key);
key = this.popRealCode(key);
key = this.formatKey(key, data);
data = this.rowsMove(data, key, true);
data = this.nodesMove(data, key, true);
if (dataIndexList.length !== data.length) {
throw new Error("data length error");
}
let s = "";
let count = 0;
let strLength = 0;
for (let x of data) {
strLength += x.length - 1;
}
while (s.length < strLength) {
for (let index = 0; index < data.length; index++) {
for (let index2 = 1; index2 < data[index].length; index2++) {
if (data[index][index2] === count) {
const asccode = data[index][0];
s += String.fromCharCode(asccode);
count += 1;
}
}
}
}
return s;
}
encode(data, key) {
const keyLen = key.length
let keyOnevalue = 0
for (let i in key){
keyOnevalue += key.charCodeAt(i)
}
data = this.strToMatrix(data);
const dataIndexList = data.map(x => x[0]);
data = this.sortMatrix(data);
data = this.popRandomIndex(data);
key = this.strToMatrix(key);
const keyIndexList = key.map(x => x[0]);
key = this.sortMatrix(key);
key = this.popRealCode(key);
key = this.formatKey(key, data);
const indexList = [...dataIndexList, ...keyIndexList];
data = this.nodesMove(data, key, false);
data = this.rowsMove(data, key, false);
data.push(indexList);
const temp = [];
for (let item of data) {
item = item.map(y => y.toString()).join("=");
item = Buffer.from(item).toString('base64');
item = item.replace(/\n/g, "");
temp.push(item);
}
data = temp.join("+==");
let move_step = Math.floor(data.split("").length / 3) + keyLen + keyOnevalue
while (move_step > 100){
move_step -= 100
}
data = this.shiftString(data, move_step)
data = Buffer.from(data).toString('base64')
return data;
}
}
const cys = new Cys();
const encodeData = cys.encode(`你好`, "asdasdasdawdawkjmnl;'kr");
console.log(encodeData);
const decodeData = cys.decode(encodeData, "asdasdasdawdawkjmnl;'kr");
console.log(decodeData);
先将明文转换为矩阵数组,然后进行位移加密
密文中加入了随机数,使得每次生成结果都不同
(base) PS D:\workSpace\g-gm> node cys.js
wqPCmsKGw4/Co8KawqPDj8KjwprChsKGwqPCqsKXwpPCgcKTwpPCo8KqwobDj8Kjw4DDgcONwqXCqsKGw47CpMOQwpvCk8KBwpPCk8KkwqrCp8OQwqbCqsK9w5DCpMOQwobDkMKjw5DCvcKPwqPDkMKjwofCpsKqwpvDj8KjwqrChsKJwqTDgMKnwo/Co8OQwpfDkMKmwqrCm8KHwqTDkMKGwovCpMOQwqvCj8KkwprCm8KPwqPDkMKnw43CpsKqwrnCicKlwprChsKKwqPCqsKvwo/CpMKqwr3Djw==
你好
(base) PS D:\workSpace\g-gm> node cys.js
wqPCmsKGw4/Co8OAw4HDjcKlwqrChsOKwqTDkMK5wovCgcKTwpPCo8KqwobDj8KjwprCo8OPwqPCmsKGw4rCo8Kqwq/DjcKBwpPCk8KlwqrCr8KKwqbCqsKjw4/CpcKawobCisKjwprCq8KPwqPCqsOBw4/CpsKqwr3Ci8Kjw4DChsKLwqPCmsKbwo/Co8OAwpfDj8KmwqrCr8KLwqTDkMKGwonCpcKawobCicKjw4DCp8KPwqPCqsKXwofCpsKqwrnCi8KkwprChsKHwqPCqsKvwo/CpMOQwpvDjw==
你好
(base) PS D:\workSpace\g-gm> node cys.js
wqLCmcKFw47CosKZwqLDjsKiwpnChcOJwqPCv8Kuw4zCgMKSwpLCosKpwoXDjsKiwr/DgMOMwqTCqcKFw4nCosKpwqLCisKAwpLCksKiwpnChcONwqLDj8K4wo7Co8K/wp7DjcKlwqnCosOPwqPCqcKFwonCpMKZwrjCjsKjw4/CvMKGwqXCqcKuwofCpcKpwp7DjMKiwr/ChcKJwqPCv8KFwobCpMKZwqbCjsKiwr/CuMKJwqXCqcKuwonCpcKpwrzChcKlwqnDgMKIwqPCpsKSwpI=
你好
(base) PS D:\workSpace\g-gm> node cys.js
wqPCmsKGw4/Co8KawqPDj8KjwprChsKIwqTCqsKXwpPCgcKTwpPCo8KqwobDj8Kjw4DDgcONwqXCqsKGw4rCo8OAwpvCi8KBwpPCk8KkwprChsOOwqXCmsKrwo/CpMOQwr3CisKmwqrCucKIwqXCqsKGw47Co8KawpfCicKmwqrDgcKHwqTDgMKGw47CpMOAwr3Cj8KkwqrCo8KHwqbCqsKnwojCo8OAwobDjsKjwqrCr8KPwqXCqsK9w4/CpsKqwq/CiMKjwprChsKKwqXCqsK9wo/CpMOAwqvCkw==
你好