file encode

标签(TAG): 文件加密  
   文件加密技术一例

 给文件加密的技术很多,其中又分为不同等级,以适合不同场合的需要.这里给出最简单的文件加密技术,即采用文件逐字节与密码异或方式对
文件进行加密,当***时,只需再运行一遍加密程序即可.

  下面是一个实例程序,能对任意一个文件进行加密,密码要求用户输入,限8位以内(当然你可以再更改).程序有很好的容错设计,这是我们应该
学习的.

/* Turbo 2.0 pass. give file a password! */

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>

void dofile(char *in_fname,char *pwd,char *out_fname);/*对文件进行加密的具体函数*/

void main(int argc,char *argv[])/*定义main()函数的命令行参数*/
{
char in_fname[30];/*用户输入的要加密的文件名*/
char out_fname[30];
char pwd[8];/*用来保存密码*/

if(argc!=4){/*容错处理*/
printf("/nIn-fname:/n");
gets(in_fname);/*得到要加密的文件名*/

printf("Password:/n");
gets(pwd);/*得到密码*/

printf("Out-file:/n");
gets(out_fname);/*得到加密后你要的文件名*/


dofile(in_fname,pwd,out_fname);
}
else{/*如果命令行参数正确,便直接运行程序*/
strcpy(in_fname,argv[1]);
strcpy(pwd,argv[2]);
strcpy(out_fname,argv[3]);
dofile(in_fname,pwd,out_fname);
}

}


/*加密子函数开始*/
void dofile(char *in_fname,char *pwd,char *out_file)
{
FILE *fp1,*fp2;
register char ch;
int j=0;
int j0=0;

fp1=fopen(in_fname,"rb");
if(fp1==NULL){
printf("cannot open in-file./n");
exit(1);/*如果不能打开要加密的文件,便退出程序*/
}
fp2=fopen(out_file,"wb");
if(fp2==NULL){
printf("cannot open or create out-file./n");
exit(1);/*如果不能建立加密后的文件,便退出*/
}
while(pwd[++j0]);
ch=fgetc(fp1);

/*加密算法开始*/
while(!feof(fp1)){
fputc(ch^pwd[j>=j0?j=0:j++],fp2);/*异或后写入fp2文件*/
ch=fgetc(fp1);
}
fclose(fp1);/*关闭源文件*/
fclose(fp2);/*关闭目标文件*/
}

/*程序结束*/

 

### 使用Python `uu` 模块进行编码 Python 的 `uu` 模块提供了简单的接口来读写 Unix-to-Unix 编码文件。这种编码方式主要用于通过电子邮件传输二进制数据。 #### 编码过程 要使用 `uu` 模块对字符串或文件内容进行编码,可以调用 `encode()` 函数: ```python import uu # 将源文件编码到目标文件 source_file_path = 'example.bin' encoded_file_path = 'example.uu' with open(source_file_path, 'rb') as source_file: with open(encoded_file_path, 'wb') as encoded_file: uu.encode(source_file, encoded_file) ``` 此代码片段展示了如何打开一个二进制文件并将其转换为 UU 编码格式保存至另一个文件中[^1]。 对于内存中的字节串也可以直接编码: ```python import io import uu input_data = b'Hello world!' output_buffer = io.BytesIO() uu.encode(io.BytesIO(input_data), output_buffer) print(output_buffer.getvalue().decode()) ``` 这段程序会创建一个包含已编码数据的新缓冲区,并打印其内容。 #### 解码过程 解码操作同样简单,只需利用 `decode()` 方法即可恢复原始数据: ```python decoded_output_path = 'decoded_example.bin' with open(encoded_file_path, 'rb') as encoded_file: with open(decoded_output_path, 'wb') as decoded_file: uu.decode(encoded_file, decoded_file) ``` 上述例子说明了怎样把之前编码过的 `.uu` 文件还原成原来的二进制形式。 #### 注意事项 需要注意的是,在 Python 3 中处理文件时应始终指定正确的模式 (`b`) 来表示正在处理的是二进制而非文本数据;另外,当涉及到网络传输或其他平台间的数据交换时,确保两端都支持相同的字符集非常重要。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值