8、文件加密程序:将待加密文件以二进制打开,读入32个字节,分别与口令异或,在将4、5、6三个字分别与0x四个a异或,即完成加密,执行第二次就解密
参考:https://blog.csdn.net/qq_72111942/article/details/126477652
不知道你这个问题是否已经解决, 如果还没有解决的话:我的理解
1.先输入已排好序的数组
2.判断输入的数应该在哪个位置
3.这个位置包括这个位置之后的数依此向后挪一位,把这个数放进去
4.整个数组输出
**以下是代码**
// Ada
#include<stdio.h>
int main(){
int a[10], n, k, j = 0;
for(int i = 0; i < 9; i++){
scanf("%d ", &a[i]);
}
scanf("%d", &n);
while(n > a[j])
{
j++;
}
for( k = 8; k >= j; k--){ //小心临界点
a[k+1] = a[k];
}
a[k+1] = n; //小心临界点
for(int i = 0; i < 10; i++){
printf("%d\n", a[i]);
}
return 0;
}
**临界点有时会出现问题,大于还是大于等于呀等等,临界点还是要先试数,不然容易想糊涂**
根据问题描述,我们可以按照以下步骤实现文件的加密和解密:
下面我们分别介绍每个步骤的具体实现。
def read_file(file_path):
with open(file_path, 'rb') as file:
content = file.read()
return content
def read_first_32_bytes(content):
return content[:32]
def xor_bytes(content, password):
encrypted_content = []
for byte in content:
encrypted_byte = byte ^ password
encrypted_content.append(encrypted_byte)
return bytes(encrypted_content)
def special_xor(content):
encrypted_content = bytearray(content)
encrypted_content[3] ^= 0xaa
encrypted_content[4] ^= 0xaa
encrypted_content[5] ^= 0xaa
return bytes(encrypted_content)
解密和加密过程是相同的,所以可以直接再次执行以上步骤即可还原密文为明文。
完整的代码如下所示:
def read_file(file_path):
with open(file_path, 'rb') as file:
content = file.read()
return content
def read_first_32_bytes(content):
return content[:32]
def xor_bytes(content, password):
encrypted_content = []
for byte in content:
encrypted_byte = byte ^ password
encrypted_content.append(encrypted_byte)
return bytes(encrypted_content)
def special_xor(content):
encrypted_content = bytearray(content)
encrypted_content[3] ^= 0xaa
encrypted_content[4] ^= 0xaa
encrypted_content[5] ^= 0xaa
return bytes(encrypted_content)
# 加密文件
def encrypt_file(file_path, password):
content = read_file(file_path)
first_32_bytes = read_first_32_bytes(content)
encrypted_first_32_bytes = xor_bytes(first_32_bytes, password)
encrypted_first_32_bytes = special_xor(encrypted_first_32_bytes)
encrypted_content = encrypted_first_32_bytes + content[32:]
return encrypted_content
# 解密文件
def decrypt_file(file_path, password):
encrypted_content = read_file(file_path)
decrypted_first_32_bytes = special_xor(encrypted_content[:32])
decrypted_first_32_bytes = xor_bytes(decrypted_first_32_bytes, password)
decrypted_content = decrypted_first_32_bytes + encrypted_content[32:]
return decrypted_content
# 测试加密文件
encrypted_content = encrypt_file("test.txt", 12345)
with open("encrypted.txt", 'wb') as file:
file.write(encrypted_content)
# 测试解密文件
decrypted_content = decrypt_file("encrypted.txt", 12345)
with open("decrypted.txt", 'wb') as file:
file.write(decrypted_content)