用异或加密解密的算法 源代码

合集下载

C语言如何使用异或(xor)加密或解密文件

C语言如何使用异或(xor)加密或解密文件

C语言如何使用异或(xor)加密或解密文件xor_encrypt.c/** XOR 加密/解密文件 */#define TRUE 1#define FALSE 0#include#include#include#include // 如果在/usr/include/找不到,可以在/usr/include/sys/复制过去// 输出信息void msg_log(char *str);// 判断文件是否存在int file_exists(char *filename);// 主函数int main(int argc, char *argv[]){int keylen, index=0;char *source, *dest, *key, fBuffer[1], tBuffer[20], ckey;FILE *fSource, *fDest;source = argv[1]; // 原文件dest = argv[2]; // 目的文件key = argv[3]; // 加密字串// 检查参数if(source==NULL || dest==NULL || key==NULL){msg_log("param error usage:xor_encrypt source dest key e.g ./xor_encrypt o.txt d.txt 123456");exit(0);}// 判断原文件是否存在if(file_exists(source)==FALSE){sprintf(tBuffer,"%s not exists",source);msg_log(tBuffer);exit(0);}// 获取key长度keylen = strlen(key);fSource = fopen(source, "rb");fDest = fopen(dest, "wb");while(!feof(fSource)){fread(fBuffer, 1, 1, fSource); // 读取1字节if(!feof(fSource)){ckey = key[index%keylen]; // 循环获取key*fBuffer = *fBuffer ^ ckey; // xor encryptfwrite(fBuffer, 1, 1, fDest); // 写入文件index ++;}}fclose(fSource);fclose(fDest);msg_log("success");exit(0);}//输出信息void msg_log(char *str){printf("%s ", str);}// 判断文件是否存在int file_exists(char *filename){return (access(filename, 0)==0);}这张图如果使用php来处理需要 2秒左右,但用C处理只需要 130毫秒。

c#rc4算法,加密解密类

c#rc4算法,加密解密类

c#rc4算法,加密解密类rc4算法,原理,以密匙⽣成256位的密匙流,然后以车轮式滚过源数据异或加密。

1/*2 * 由SharpDevelop创建。

3 * ⽤户: YISH4 * ⽇期: 04/04/20155 * 时间: 03:016 *7 * 要改变这种模板请点击⼯具|选项|代码编写|编辑标准头⽂件8*/9using System;1011namespace Libraries12 {13///<summary>14/// Description of CryptoGraphy.15///</summary>16public class RC4Crypt:IDisposable{17byte[] S;18byte[] T;19byte[] K;20byte[] k;21public RC4Crypt() { }22public RC4Crypt(byte[] key){23this.K=key;24 }25public byte[] Key26 {27get28 {29return K;30 }31set32 {33 K = value;34 }35 }36//初始化状态向量S和临时向量T,供keyStream⽅法调⽤37void initial(){38if (S == null || T == null)39 {40 S = new byte[256];41 T = new byte[256];42 }43for (int i = 0; i < 256; ++i) {44 S[i]=(byte)i;45 T[i] = K[i % K.Length];46 }47 }48//初始排列状态向量S,供keyStream⽅法调⽤49void ranges(){50int j=0;51for (int i = 0; i < 256; ++i) {52 j=(j+S[i]+T[i])&0xff;53 S[i]=(byte)((S[i]+S[j])&0xff);54 S[j]=(byte)((S[i]-S[j])&0xff);55 S[i]=(byte)((S[i]-S[j])&0xff);56 }57 }58//⽣成密钥流59//len:明⽂为len个字节60void keyStream(int len){61 initial();62 ranges();63int i=0,j=0,t=0;64 k=new byte[len];65for (int r = 0; r < len; r++) {66 i=(i+1)&0xff;67 j=(j+S[i])&0xff;6869 S[i]=(byte)((S[i]+S[j])&0xff);70 S[j]=(byte)((S[i]-S[j])&0xff);71 S[i]=(byte)((S[i]-S[j])&0xff);7273 t=(S[i]+S[j])&0xff;74 k[r]=S[t];75 }76 }7778public byte[] EncryptByte(byte[] data){79//⽣产密匙流80 keyStream(data.Length);81for (int i = 0; i < data.Length; i++) {82 k[i]=(byte)(data[i]^k[i]);83 }84return k;85 }8687public byte[] DecryptByte(byte[] data){88return EncryptByte(data);89 }9091//是否回收完毕92bool _disposed;93public void Dispose()94 {95 Dispose(true);96 GC.SuppressFinalize(this);97 }98 ~RC4Crypt()99 {100 Dispose(false);101 }102//这⾥的参数表⽰⽰是否需要释放那些实现IDisposable接⼝的托管对象103protected virtual void Dispose(bool disposing)104 {105if (_disposed) return;//如果已经被回收,就中断执⾏106if (disposing)107 {108//TODO:释放那些实现IDisposable接⼝的托管对象109110 }111//TODO:释放⾮托管资源,设置对象为null112 S = null;113 T = null;114 K = null;115 k = null;116 _disposed = true;117 }118 }119 }。

AESECB加密算法C语言代码实现

AESECB加密算法C语言代码实现

AESECB加密算法C语言代码实现要实现AESECB加密算法的C语言代码,需要先了解AES算法的基本原理和步骤。

以下是一个使用C语言实现AESECB加密算法的示例代码:```c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <openssl/aes.h>//定义密钥长度#define KEY_LENGTH 16//ECBAES加密函数void AESEncrypt_ECB(const unsigned char* plainText, int plainTextLength, unsigned char* cipherText,const unsigned char* key)//创建AES密钥结构体AES_KEY aesKey;//设置加密密码AES_set_encrypt_key(key, KEY_LENGTH * 8, &aesKey);//加密数据AES_ecb_encrypt(plainText, cipherText, &aesKey, AES_ENCRYPT);//ECBAES解密函数void AESDecrypt_ECB(const unsigned char* cipherText, int cipherTextLength, unsigned char* plainText,const unsigned char* key)//创建AES密钥结构体AES_KEY aesKey;//设置解密密码AES_set_decrypt_key(key, KEY_LENGTH * 8, &aesKey);//解密数据AES_ecb_encrypt(cipherText, plainText, &aesKey, AES_DECRYPT);int mai//指定原始明文和密钥unsigned char plainText[] = "Hello, World!";unsigned char key[] = "secretkey";//计算明文长度int plainTextLength = strlen(plainText);//计算加密后的数据长度int cipherTextLength = ((plainTextLength / KEY_LENGTH) + 1) * KEY_LENGTH;//分配加密后数据的内存unsigned char* cipherText = (unsignedchar*)malloc(cipherTextLength);//加密数据AESEncrypt_ECB(plainText, plainTextLength, cipherText, key);//打印加密后的结果printf("Cipher text: ");for (int i = 0; i < cipherTextLength; i++)printf("%02x ", cipherText[i]);}printf("\n");//分配解密后数据的内存unsigned char* decryptedText = (unsignedchar*)malloc(cipherTextLength);//解密数据AESDecrypt_ECB(cipherText, cipherTextLength, decryptedText, key);//打印解密后的结果printf("Decrypted text: %s\n", decryptedText);//释放已分配的内存free(cipherText);free(decryptedText);return 0;```上述代码使用了OpenSSL库提供的AES函数来实现ECB模式的AES加密和解密操作。

php数字加密与解密代码

php数字加密与解密代码

php数字加密与解密代码PHP数字加密与解密是一种常见的安全技术,用于保护敏感数据的传输和存储。

通过加密,可以将数字转化为一串看似无规律的字符,只有拥有相应解密密钥的人才能将其还原为原始数字。

下面将介绍一种使用PHP进行数字加密与解密的方法。

我们需要使用一个密钥来进行加密和解密操作。

这个密钥可以是任意的字符串,但需要确保其安全性,不易被他人猜测到。

加密操作可以通过PHP中的加密函数实现,例如使用md5函数进行加密。

下面是一个示例代码:```php<?phpfunction encrypt($number, $key) {$encrypted = md5($key . $number);return $encrypted;}$number = 12345;$key = "mySecretKey";$encryptedNumber = encrypt($number, $key);echo "加密后的数字:" . $encryptedNumber;>```在上述代码中,encrypt函数接受两个参数:要加密的数字和密钥。

函数内部使用md5函数将密钥和数字拼接后进行加密,并返回加密后的结果。

最后,我们将加密后的数字输出到屏幕上。

解密操作则需要使用相同的密钥进行反向操作。

下面是一个示例代码:```php<?phpfunction decrypt($encryptedNumber, $key) {$decrypted = substr($encryptedNumber, strlen($key));return $decrypted;}$encryptedNumber = "2c6ee24b09816a6f14e68b4e97a2d7b7"; $key = "mySecretKey";$decryptedNumber = decrypt($encryptedNumber, $key);echo "解密后的数字:" . $decryptedNumber;>```在上述代码中,decrypt函数接受两个参数:要解密的数字和密钥。

DES加密算法与解密(带流程图)

DES加密算法与解密(带流程图)

DES加密算法与解密(带流程图)一、DES加密及解密算法程序源代码:#include <iostream>using namespace std;const static char IP_Table[] = { //IP_Table置换58, 50, 42, 34, 26, 18, 10, 2,60, 52, 44, 36, 28, 20, 12, 4,62, 54, 46, 38, 30, 22, 14, 6,64, 56, 48, 40, 32, 24, 16, 8,57, 49, 41, 33, 25, 17, 9, 1,59, 51, 43, 35, 27, 19, 11, 3,61, 53, 45, 37, 29, 21, 13, 5,63, 55, 47, 39, 31, 23, 15, 7};const static char Final_Table[] = { //最终置换40, 8, 48, 16, 56, 24, 64, 32,39, 7, 47, 15, 55, 23, 63, 31,38, 6, 46, 14, 54, 22, 62, 30,37, 5, 45, 13, 53, 21, 61, 29,36, 4, 44, 12, 52, 20, 60, 28,35, 3, 43, 11, 51, 19, 59, 27,34, 2, 42, 10, 50, 18, 58, 26,33, 1, 41, 9, 49, 17, 57, 25};const static char S_Box[8][64] = {//s_box/* S1 */{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13},/* S2 */{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10,14, 5, 2, 8, 4,3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14},/* S5 */{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3},/* S6 */{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13},/* S7 */{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12},/* S8 */{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}const static char Rar_Table[] = { //压缩置换14, 17, 11, 24, 1, 5,3, 28, 15, 6, 21, 10,23, 19, 12, 4, 26, 8,16, 7, 27, 20, 13, 2,41, 52, 31, 37, 47, 55,30, 40, 51, 45, 33, 48,44, 49, 39, 56, 34, 53,46, 42, 50, 36, 29, 32};const static char Exp_Table[] = { //扩展置换32, 1, 2, 3, 4, 5,4, 5, 6, 7, 8, 9,8, 9, 10, 11, 12, 13,12, 13, 14, 15, 16, 17,16, 17, 18, 19, 20, 21,20, 21, 22, 23, 24, 25,24, 25, 26, 27, 28, 29,28, 29, 30, 31, 32, 1const static char P_Table[]={ //P置换16, 7, 20, 21,29, 12, 28, 17,1, 15, 23, 26,5, 18, 31, 10,2, 8, 24, 14,32, 27, 3, 9,19, 13, 30, 6,22, 11, 4, 25};const static char KeyRar_Table[]={57, 49, 41, 33, 25, 17, 9,1, 58, 50, 42, 34, 26, 18,10, 2, 59, 51, 43, 35, 27,19, 11, 3, 60, 52, 44, 36,63, 55, 47, 39, 31, 23, 15,7, 62, 54, 46, 38, 30, 22,14, 6, 61, 53, 45, 37, 29,21, 13, 5, 28, 20, 12, 4};//设置全局变量,16轮密钥bool key[16][48]={{0}};void ByteToBit(bool *Out,char *In,int bits) //字节到位转换函数{int i;for(i=0;i<bits;i++)Out[i]=(In[i/8]>>(i%8))&1;}void BitToByte(char *Out,bool *In,int bits)//位到字节转换函数{int i;for(i=0;i<bits/8;i++)Out[i]=0;for(i=0;i<bits;i++)Out[i/8]|=In[i]<<(i%8);}void Xor(bool *InA,const bool *InB,int length) //按位异或for(int i=0;i<length;i++)InA[i]^=InB[i];}void keyfc(char *In) //密钥生成函数{int i,j=0,mov,k,m;bool* key0 = new bool[56];bool* keyin = new bool[64];bool temp;ByteToBit(keyin,In,64); //字节到位的转换for(i=0;i<56;i++) //密钥压缩为56位key0[i]=keyin[KeyRar_Table[i]-1];for(i=0;i<16;i++) //16轮密钥产生{if(i==0||i==1||i==8||i==15)mov=1;elsemov=2;for(k=0;k<mov;k++) //分左右两块循环左移{for(m=0;m<8;m++){temp=key0[m*7];for(j=m*7;j<m*7+7;j++)key0[j]=key0[j+1];key0[m*7+6]=temp;}temp=key0[0];for(m=0;m<27;m++)key0[m]=key0[m+1];key0[27]=temp;temp=key0[28];for(m=28;m<55;m++)key0[m]=key0[m+1];key0[55]=temp;}for(j=0;j<48;j++) //压缩置换并储存key[i][j]=key0[Rar_Table[j]-1];}delete[] key0;delete[] keyin;}void DES(char Out[8],char In[8],bool Type)//加密核心程序,Type=0时加密,反之解密{bool* MW = new bool[64];bool* tmp = new bool[32];bool* PMW = new bool[64];bool* kzmw = new bool[48];bool* keytem = new bool[48];bool* ss = new bool[32];int hang,lie,i;ByteToBit(PMW,In,64);for(int j=0;j<64;j++){MW[j]=PMW[IP_Table[j]-1]; //初始置换}bool *Li=&MW[0],*Ri=&MW[32];for(i=0;i<48;i++) //右明文扩展置换kzmw[i]=Ri[Exp_Table[i]-1];if(Type==0) //DES加密过程{for(int lun=0;lun<16;lun++){for(i=0;i<32;i++)ss[i]=Ri[i];for(i=0;i<48;i++) //右明文扩展置换kzmw[i]=Ri[Exp_Table[i]-1];for(i=0;i<48;i++)keytem[i]=key[lun][i];Xor(kzmw,keytem,48);/*S盒置换*/for(i=0;i<8;i++)hang=kzmw[i*6]*2+kzmw[i*6+5];lie=kzmw[i*6+1]*8+kzmw[i*6+2]*4+kzmw[i*6+3] *2+kzmw[i*6+4];tmp[i*4+3]=S_Box[i][(hang+1)*16+lie]%2;tmp[i*4+2]=(S_Box[i][(hang+1)*16+lie]/2)%2 ;tmp[i*4+1]=(S_Box[i][(hang+1)*16+lie]/4)%2 ;tmp[i*4]=(S_Box[i][(hang+1)*16+lie]/8)%2;}for(i=0;i<32;i++) //P置换Ri[i]=tmp[P_Table[i]-1];Xor(Ri,Li,32); //异或for(i=0;i<32;i++) //交换左右明文Li[i]=ss[i];}}for(i=0;i<32;i++){tmp[i]=Li[i];Li[i]=Ri[i];Ri[i]=tmp[i];}for(i=0;i<64;i++)PMW[i]=MW[Final_Table[i]-1];BitToByte(Out,PMW,64); //位到字节的转换}else //DES解密过程{for(int lun=15;lun>=0;lun--){for(i=0;i<32;i++)ss[i]=Ri[i];for(i=0;i<48;i++) //右明文扩展置换kzmw[i]=Ri[Exp_Table[i]-1];for(i=0;i<48;i++)keytem[i]=key[lun][i];Xor(kzmw,keytem,48);/*S盒置换*/for(i=0;i<8;i++){hang=kzmw[i*6]*2+kzmw[i*6+5];lie=kzmw[i*6+1]*8+kzmw[i*6+2]*4+kzmw[i*6+3] *2+kzmw[i*6+4];tmp[i*4+3]=S_Box[i][(hang+1)*16+lie]%2;tmp[i*4+2]=(S_Box[i][(hang+1)*16+lie]/2)%2 ;tmp[i*4+1]=(S_Box[i][(hang+1)*16+lie]/4)%2 ;tmp[i*4]=(S_Box[i][(hang+1)*16+lie]/8)%2; }for(i=0;i<32;i++) //P置换Ri[i]=tmp[P_Table[i]-1];Xor(Ri,Li,32); //异或for(i=0;i<32;i++) //交换左右明文{Li[i]=ss[i];}}for(i=0;i<32;i++){tmp[i]=Li[i];Li[i]=Ri[i];Ri[i]=tmp[i];}for(i=0;i<64;i++)PMW[i]=MW[Final_Table[i]-1]; BitToByte(Out,PMW,64); //位到字节的转换}delete[] MW;delete[] tmp;delete[] PMW;delete[] kzmw;delete[] keytem;delete[] ss;}bool RunDes(char *Out, char *In, int datalength, char *Key, bool Type) //加密运行函数,判断输入以及对输入文本8字节分割{if( !( Out && In && Key && (datalength=(datalength+7)&0xfffffff8) ) ) return false;keyfc(Key);for(int i=0,j=datalength%8; i<j; ++i,Out+=8,In+=8)DES(Out, In, Type);return true;}int main(){char* Ki = new char[8];char Enter[]="This is the test of DES!"; char* Print = new char[200];int len = sizeof(Enter);int i_mf;cout << "请输入密钥(8位):" <<"\n"; for(i_mf=0;i_mf<8;i_mf++)cin >> Ki[i_mf];cout << "\n";RunDes(Print,Enter,len,Ki,0);//加密cout << "----加密前----" << "\n";for(i_mf=0;i_mf<len;i_mf++)cout << Enter[i_mf];cout << "\n\n";cout << "----加密后----" << "\n";for(i_mf=0;i_mf<len;i_mf++)cout<<Print[i_mf];cout << "\n\n";//此处进行不同密钥输入测试cout << "请输入密钥(8位):" <<"\n"; for(i_mf=0;i_mf<8;i_mf++)cin >> Ki[i_mf];cout << "\n";RunDes(Enter,Print,len,Ki,1);//解密cout << "----解密后----" << "\n";for(i_mf=0;i_mf<len;i_mf++)cout << Enter[i_mf];cout << endl;delete[] Ki;delete[] Print;return 0;}二、程序编译、运行结果图:三、程序总体框架图:读取待加密文本输入密钥DES 加密显示加密后文本再次输入密钥DES 解密显示解密后文本显示错误解密信息密钥错误密钥正确四、程序实现流程图:Enter = 待加密文本分割Enter ,8字节为一段,不足补加,段数为N 初始化:*Print ,i=0,j=0文本第i 段,转为二进制64位初始置换(IP_Table )文本段分为左右两部分左部分(32位)右部分(32)输入8字节密钥转为二进制64位密钥压缩KeyRar_Table (56位)形成16轮密钥合并形成子密钥(48位)S 置换(S_Box )P 置换(P_Table )左右交换,j++最终置换(Final_Table )J<16扩展置换(Exp_Table )i<N异或异或NoYes存入*Print ,i++DES 加密过程结束,输出Print YesNoDES 解密过程为以上逆过程。

C语言加密与解密算法

C语言加密与解密算法

C语言加密与解密算法在计算机科学与信息安全领域,加密与解密算法起着至关重要的作用。

加密算法用于将原始数据转换为不可读的密文,而解密算法则用于将密文还原为可读的原始数据。

C语言是一种常用的编程语言,具备高效性和灵活性,适用于加密与解密算法的开发。

本文将介绍几种常用的C语言加密与解密算法。

一、凯撒密码算法凯撒密码算法是一种最简单的替换加密算法,通过将字母按照固定的偏移量进行替换来实现加密与解密。

以下是一个简单的C语言凯撒密码实现例子:```c#include <stdio.h>void caesarEncrypt(char* message, int key) {int i = 0;while (message[i] != '\0') {if (message[i] >= 'a' && message[i] <= 'z') {message[i] = (message[i] - 'a' + key) % 26 + 'a';} else if (message[i] >= 'A' && message[i] <= 'Z') {message[i] = (message[i] - 'A' + key) % 26 + 'A';}i++;}}void caesarDecrypt(char* message, int key) {int i = 0;while (message[i] != '\0') {if (message[i] >= 'a' && message[i] <= 'z') {message[i] = (message[i] - 'a' - key + 26) % 26 + 'a'; } else if (message[i] >= 'A' && message[i] <= 'Z') {message[i] = (message[i] - 'A' - key + 26) % 26 + 'A'; }i++;}}int main() {char message[] = "Hello, World!";int key = 3;printf("Original message: %s\n", message);caesarEncrypt(message, key);printf("Encrypted message: %s\n", message);caesarDecrypt(message, key);printf("Decrypted message: %s\n", message);return 0;}```以上程序演示了凯撒密码的加密与解密过程,通过指定偏移量实现对消息的加密与解密。

加密系列MD5加密和解密算法详解代码示例

加密系列MD5加密和解密算法详解代码示例

加密系列MD5加密和解密算法详解代码示例MD5加密算法是一种广泛应用的密码加密算法,它将任意长度的数据映射为固定长度的128位哈希值。

MD5加密算法是不可逆的,即通过密文无法还原得到原始数据。

MD5加密算法的实现可以通过编写代码来完成。

下面是一个示例的MD5加密算法的代码:```import hashlibdef md5_encrypt(data):md5 = hashlib.md5md5.update(data.encode('utf-8'))return md5.hexdigestif __name__ == '__main__':data = input("请输入需要加密的数据:")encrypted_data = md5_encrypt(data)print("加密结果为:", encrypted_data)```以上代码实现了一个简单的MD5加密算法。

首先导入了`hashlib`模块,该模块提供了一系列用于数据加密的算法,包括MD5算法。

`md5_encrypt`函数接收一个字符串作为输入数据,并将其转换为字节流形式,然后使用`hashlib.md5`方法创建了一个MD5对象。

接着,通过调用MD5对象的`update`方法将输入数据添加到加密流程中。

最后,通过调用MD5对象的`hexdigest`方法获得加密后的结果,并将其返回。

在`if __name__ == '__main__'`下方的代码段中,首先获取用户输入的数据,然后调用`md5_encrypt`函数对其进行加密,并将结果打印到控制台。

下面是MD5解密算法的示例代码:```import hashlibdef md5_decrypt(encrypted_data):md5 = hashlib.md5md5.update(encrypted_data.encode('utf-8'))return md5.hexdigestif __name__ == '__main__':encrypted_data = input("请输入需要解密的数据:")decrypted_data = md5_decrypt(encrypted_data)print("解密结果为:", decrypted_data)```以上代码实现了一个简单的MD5解密算法。

详解XOR(异或)运算加密

详解XOR(异或)运算加密

详解XOR(异或)运算加密逻辑运算之中,除了 AND 和 OR,还有⼀种 XOR 运算,中⽂称为"异或运算"。

它的定义是:两个值相同时,返回false,否则返回true。

也就是说,XOR可以⽤来判断两个值是否不同。

JavaScript 语⾔的⼆进制运算,有⼀个专门的 XOR 运算符,写作^。

如果两个⼆进制位相同,就返回0,表⽰false;否则返回1,表⽰true。

XOR 的应⽤XOR 运算有⼀个很奇妙的特点:如果对⼀个值连续做两次 XOR,会返回这个值本⾝。

上⾯代码中,原始值是1010,再任意选择⼀个值(上例是1111),做两次 XOR,最后总是会得到原始值1010。

这在数学上是很容易证明的。

加密应⽤XOR 的这个特点,使得它可以⽤于信息的加密。

上⾯代码中,原始信息是message,密钥是key,第⼀次 XOR 会得到加密⽂本cipherText。

对⽅拿到以后,再⽤key做⼀次 XOR 运算,就会还原得到message。

完美保密性⼆战期间,各国为了电报加密,对密码学进⾏了⼤量的研究和实践,其中就包括 XOR 加密。

战后,美国数学家⾹农将他的研究成果公开发表,证明了只要满⾜两个条件,XOR 加密是⽆法破解的。

key的长度⼤于等于messagekey必须是⼀次性的,且每次都要随机产⽣理由很简单,如果每次的key都是随机的,那么产⽣的CipherText具有所有可能的值,⽽且是均匀分布,⽆法从CipherText看出message的任何特征。

也就是说,它具有最⼤的"信息熵",因此完全不可能破解。

这被称为 XOR 的"完美保密性"(perfect secrecy)。

满⾜上⾯两个条件的key,叫做 one-time pad(缩写为OTP),意思是"⼀次性密码本",因为以前这样的key都是印刷成密码本,每次使⽤的时候,必须从其中挑选key。

文件加密源代码

文件加密源代码

#include<stdio.h>#include<stdlib.h>#include<string.h>void add_file(char *in_fname,char *pwd,char *out_fname);void main(int argc,char *argv[]){char in_fname[30];//用户输入的要加密的文件名char out_fname[30];char del_fname[36]="del "; //删除文件名及命令int i;char pwd[20];//用来保存密码printf("功能:实现文件的加密和解密!\n注意:应用程序需跟文件放在同一个目录下!\n\n\n");if(argc!=4) //容错处理{printf("输入需要加密或者解密的文件(加后缀):\n");gets(in_fname); //得到要加密的文件名printf("输入密钥:\n");gets(pwd); //得到密码printf("输入解密或加密后的新文件名(加后缀):\n");gets(out_fname);//得到加密后你要的文件名add_file(in_fname,pwd,out_fname);}else //如果命令行参数正确,便直接运行程序{strcpy(in_fname,argv[1]);strcpy(pwd,argv[2]);strcpy(out_fname,argv[3]);add_file(in_fname,pwd,out_fname);}for(i=0;in_fname[i]!='\0';i++){del_fname[i+4]=in_fname[i];}del_fname[i+4]='/';del_fname[i+5]='p';del_fname[i+6]='\0';system(del_fname);}/*********加密子函数开始************/void add_file(char *in_fname,char *pwd,char *out_file){FILE *fp1,*fp2;register char ch;int j=0;int jj=0;fp1=fopen(in_fname,"rb");if(fp1==NULL){printf("文件打开失败!\n");system("echo Wscript.sleep 3000 >y.vbs ");system("call y.vbs &del y.vbs ");exit(1); //如果不能打开要加密的文件,便退出程序}fp2=fopen(out_file,"wb");if(fp2==NULL){printf("新建文件失败!\n");system("echo Wscript.sleep 3000 >y.vbs ");system("call y.vbs &del y.vbs ");exit(1); //如果不能建立加密后的文件,便退出}while(pwd[++jj]) ; //算出密钥长度,保存至j0ch=fgetc(fp1); //加密算法开始while(!feof(fp1)) //测试文件是否结束{fputc(ch^pwd[j>=jj?j=0:j++],fp2);//异或后写入fp2文件,加密和解密互逆ch=fgetc(fp1);}fclose(fp1);//关闭源文件fclose(fp2);//关闭目标文件}//void main()//{// system("del 1.c/p");//// while(1);////}。

xortool用法 -回复

xortool用法 -回复

xortool用法-回复Xortool是一个用于自动破解单字符加密和重复密钥异或(XOR)加密算法的Python脚本。

这个工具可以帮助我们破解加密信息并恢复原始文本。

本文将详细介绍如何安装和使用Xortool来解密加密文件。

第一部分:安装Xortool首先,我们需要确保Python环境已正确安装在计算机上。

可以在终端窗口中输入"python version"来检查Python的版本。

如果没有安装,我们可以从Python官方网站下载并安装最新版本。

接下来,我们需要安装Xortool脚本。

可以从github上下载xortool的源代码,并将其解压到一个目录中。

然后,在终端窗口中导航到该目录并运行以下命令:python setup.py install这将自动安装xortool并将其添加到系统的可执行路径中。

第二部分:使用Xortool解密文件现在我们已经安装了Xortool,可以开始使用它来解密加密文件了。

首先,我们需要找到一个加密过的文件,然后使用Xortool进行解密。

假设我们有一个名为encrypted.txt的文件,我们可以使用以下命令来运行xortool:xortool encrypted.txtXortool将自动分析文件并尝试使用不同的密钥来解密它。

该工具将生成多个解密的候选结果,我们可以通过检查它们的输出来找到正确的解密。

接下来,我们可以使用-x选项来指定一个字符集,该字符集将用于生成解密结果。

例如,如果我们知道原始文本只包含英文字母,我们可以使用以下命令进行解密:xortool -x'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' encrypted.txtxortool将使用提供的字符集生成解密结果,并将它们输出到终端窗口。

此外,我们还可以通过使用-m选项来指定一个最小重复字节数。

这对于重复密钥异或加密算法非常有用。

c语言解密代码

c语言解密代码

c语言解密代码下面是一个简单的`C`语言加密解密代码,实现了凯撒加密的功能:```c#include<stdio.h>#include<stdlib.h>#include<string.h>// 函数 encode() 将字母顺序推后 n 位,实现文件加密功能void encode(char str[], int n){char c;int i;for (i = 0; i < strlen(str); ++i){// 遍历字符串c = str[i];if (c >='a' && c <='z'){// c 是小写字母if (c + n % 26 <='z'){// 若加密后不超出小写字母范围str[i] = (char)(c + n % 26);}else{// 加密后超出小写字母范围,从头开始循环小写字母 str[i] = (char)(c + n % 26 - 26);}elseif (c >='A' && c <='Z'){// c 为大写字母if (c + n % 26 <= 'Z'){// 加密后不超出大写字母范围str[i] = (char)(c + n % 26);}else{// 加密后超出大写字母范围,从头开始循环大写字母 str[i] = (char)(c + n % 26 - 26);}}else{// 不是字母,不加密str[i] = c;printf("\nAfter encode: \n");puts(str);}}// 输出加密后的字符串printf("\nAfter encode: \n");puts(str);}// 实现解密功能,将字母顺序前移 n 位void decode(char str[], int n){int i;for (i = 0; i < strlen(str); ++i){c = str[i];if (c >='a' && c <='z'){// 解密后还为小写字母,直接解密if (c - n % 26 >='a'){str[i] = (char)(c - n % 26);}else{// 解密后不为小写字母了,通过循环小写字母处理为小写字母 str[i] = (char)(c - n % 26 + 26);}}elseif (c >= 'A' && c <='Z'){// c 为大写字母if (c - n % 26 >='A'){// 解密后还为大写字母str[i] = (char)(c - n % 26);}else{// 解密后不为大写字母了,循环大写字母,处理为大写字母str[i] = (char)(c - n % 26 + 26);}}else{// 不是字母,不加密str[i] = c;}}// 输出解密后的字符串printf("\nAfter decode: \n");puts(str);}int main(){char str[20];int n;printf("请输入字符串(以空格结束输入):\n");gets(str);printf("请输入密钥(1-25的整数):\n");scanf("%d", &n);printf("加密前的字符串为:%s\n", str);encode(str, n);printf("加密后的字符串为:%s\n", str);decode(str, n);printf("解密后的字符串为:%s\n", str);return 0;}```在上述代码中,加密函数`encode()`通过将字符串中的每个字符循环向后移动`n`位实现加密,解密函数`decode()`通过将字符串中的每个字符循环向前移动`n`位实现解密。

C#加密解密(DES,AES,Base64,md5,SHA256,RSA,RC4)

C#加密解密(DES,AES,Base64,md5,SHA256,RSA,RC4)

C#加密解密(DES,AES,Base64,md5,SHA256,RSA,RC4)⼀:异或^简单加解密(数字类型)1:原理:异或⽤于⽐较两个⼆进制数的相应位,在执⾏按位"异或"运算时,如果两个⼆进制数的相应位都为1或者都为0,则返回0;如果两个⼆进制数的相应位其中⼀个为1另⼀个为0,则返回1.//对数字加密int P_int_Num, P_int_Key;//定义两个值类型变量string Encryptstr = (P_int_Num ^ P_int_Key).ToString();//加密数值//对数字解密int P_int_Key, P_int_Encrypt;//定义两个值类型变量string Encryptstr =(P_int_Encrypt ^ P_int_Key).ToString();//解密数值⼆:加密解密类public class JiaMiJieMi{#region DES对称加密解密///<summary>加密字符串///</summary>///<param name="strText">需被加密的字符串</param>///<param name="strEncrKey">密钥</param>///<returns></returns>public static string DesEncrypt(string strText, string strEncrKey){try{byte[] byKey = null;byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));DESCryptoServiceProvider des = new DESCryptoServiceProvider();byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);MemoryStream ms = new MemoryStream();CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);cs.Write(inputByteArray, 0, inputByteArray.Length);cs.FlushFinalBlock();return Convert.ToBase64String(ms.ToArray());}catch{return"";}}///<summary>解密字符串///</summary>///<param name="strText">需被解密的字符串</param>///<param name="sDecrKey">密钥</param>///<returns></returns>public static string DesDecrypt(string strText, string sDecrKey){try{byte[] byKey = null;byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };byte[] inputByteArray = new Byte[strText.Length];byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));DESCryptoServiceProvider des = new DESCryptoServiceProvider();inputByteArray = Convert.FromBase64String(strText);MemoryStream ms = new MemoryStream();CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);cs.Write(inputByteArray, 0, inputByteArray.Length);cs.FlushFinalBlock();Encoding encoding = new UTF8Encoding();return encoding.GetString(ms.ToArray());}catchreturn null;}}///<summary>加密⽂件//////</summary>///<param name="m_InFilePath">原路径</param>///<param name="m_OutFilePath">加密后的⽂件路径</param>///<param name="strEncrKey">密钥</param>public static void DesEncryptFile(string m_InFilePath, string m_OutFilePath, string strEncrKey){try{byte[] byKey = null;byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);fout.SetLength(0);//Create variables to help with read and write.byte[] bin = new byte[100]; //This is intermediate storage for the encryption.long rdlen = 0; //This is the total number of bytes written.long totlen = fin.Length; //This is the total length of the input file.int len; //This is the number of bytes to be written at a time.DES des = new DESCryptoServiceProvider();CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);//Read from the input file, then encrypt and write to the output file.while (rdlen < totlen){len = fin.Read(bin, 0, 100);encStream.Write(bin, 0, len);rdlen = rdlen + len;}encStream.Close();fout.Close();fin.Close();}catch{}}///<summary>解密⽂件//////</summary>///<param name="m_InFilePath">被解密路径</param>///<param name="m_OutFilePath">解密后的路径</param>///<param name="sDecrKey">密钥</param>public static void DesDecryptFile(string m_InFilePath, string m_OutFilePath, string sDecrKey){try{byte[] byKey = null;byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);fout.SetLength(0);//Create variables to help with read and write.byte[] bin = new byte[100]; //This is intermediate storage for the encryption.long rdlen = 0; //This is the total number of bytes written.long totlen = fin.Length; //This is the total length of the input file.int len; //This is the number of bytes to be written at a time.DES des = new DESCryptoServiceProvider();CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);//Read from the input file, then encrypt and write to the output file.while (rdlen < totlen){len = fin.Read(bin, 0, 100);encStream.Write(bin, 0, len);rdlen = rdlen + len;}encStream.Close();fout.Close();fin.Close();catch{}}#endregion#region对称加密算法AES RijndaelManaged加密解密private static readonly string Default_AES_Key = "@#kim123";private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79,0x53,0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F };public static string AES_Encrypt(string encryptString){return AES_Encrypt(encryptString, Default_AES_Key);}public static string AES_Decrypt(string decryptString){return AES_Decrypt(decryptString, Default_AES_Key);}///<summary>对称加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是块式加密算法) //////</summary>///<param name="encryptString">待加密字符串</param>///<param name="encryptKey">加密密钥,须半⾓字符</param>///<returns>加密结果字符串</returns>public static string AES_Encrypt(string encryptString, string encryptKey){encryptKey = GetSubString(encryptKey, 32, "");encryptKey = encryptKey.PadRight(32, '');RijndaelManaged rijndaelProvider = new RijndaelManaged();rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32));rijndaelProvider.IV = Keys;ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();byte[] inputData = Encoding.UTF8.GetBytes(encryptString);byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);return Convert.ToBase64String(encryptedData);}///<summary>对称加密算法AES RijndaelManaged解密字符串//////</summary>///<param name="decryptString">待解密的字符串</param>///<param name="decryptKey">解密密钥,和加密密钥相同</param>///<returns>解密成功返回解密后的字符串,失败返回空</returns>public static string AES_Decrypt(string decryptString, string decryptKey){try{decryptKey = GetSubString(decryptKey, 32, "");decryptKey = decryptKey.PadRight(32, '');RijndaelManaged rijndaelProvider = new RijndaelManaged();rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);rijndaelProvider.IV = Keys;ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();byte[] inputData = Convert.FromBase64String(decryptString);byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);return Encoding.UTF8.GetString(decryptedData);}catch{return string.Empty;}}///<summary>///按字节长度(按字节,⼀个汉字为2个字节)取得某字符串的⼀部分///</summary>///<param name="sourceString">源字符串</param>///<param name="length">所取字符串字节长度</param>///<param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,⼀般为"...")</param> ///<returns>某字符串的⼀部分</returns>private static string GetSubString(string sourceString, int length, string tailString){return GetSubString(sourceString, 0, length, tailString);}///<summary>///按字节长度(按字节,⼀个汉字为2个字节)取得某字符串的⼀部分///</summary>///<param name="sourceString">源字符串</param>///<param name="startIndex">索引位置,以0开始</param>///<param name="length">所取字符串字节长度</param>///<param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,⼀般为"...")</param>///<returns>某字符串的⼀部分</returns>private static string GetSubString(string sourceString, int startIndex, int length, string tailString){string myResult = sourceString;//当是⽇⽂或韩⽂时(注:中⽂的范围:\u4e00 - \u9fa5, ⽇⽂在\u0800 - \u4e00, 韩⽂为\xAC00-\xD7A3)if (System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\u0800-\u4e00]+") ||System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\xAC00-\xD7A3]+")){//当截取的起始位置超出字段串长度时if (startIndex >= sourceString.Length){return string.Empty;}else{return sourceString.Substring(startIndex,((length + startIndex) > sourceString.Length) ? (sourceString.Length - startIndex) : length); }}//中⽂字符,如"中国⼈民abcd123"if (length <= 0){return string.Empty;}byte[] bytesSource = Encoding.Default.GetBytes(sourceString);//当字符串长度⼤于起始位置if (bytesSource.Length > startIndex){int endIndex = bytesSource.Length;//当要截取的长度在字符串的有效长度范围内if (bytesSource.Length > (startIndex + length)){endIndex = length + startIndex;}else{ //当不在有效范围内时,只取到字符串的结尾length = bytesSource.Length - startIndex;tailString = "";}int[] anResultFlag = new int[length];int nFlag = 0;//字节⼤于127为双字节字符for (int i = startIndex; i < endIndex; i++){if (bytesSource[i] > 127){nFlag++;if (nFlag == 3){nFlag = 1;}}else{nFlag = 0;}anResultFlag[i] = nFlag;}//最后⼀个字节为双字节字符的⼀半if ((bytesSource[endIndex - 1] > 127) && (anResultFlag[length - 1] == 1)){length = length + 1;}byte[] bsResult = new byte[length];Array.Copy(bytesSource, startIndex, bsResult, 0, length);myResult = Encoding.Default.GetString(bsResult);myResult = myResult + tailString;return myResult;}return string.Empty;}///<summary>///加密⽂件流///</summary>///<param name="fs"></param>///<returns></returns>public static CryptoStream AES_EncryptStrream(FileStream fs, string decryptKey){decryptKey = GetSubString(decryptKey, 32, "");decryptKey = decryptKey.PadRight(32, '');RijndaelManaged rijndaelProvider = new RijndaelManaged();rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);rijndaelProvider.IV = Keys;ICryptoTransform encrypto = rijndaelProvider.CreateEncryptor();CryptoStream cytptostreamEncr = new CryptoStream(fs, encrypto, CryptoStreamMode.Write);return cytptostreamEncr;}///<summary>///解密⽂件流///</summary>///<param name="fs"></param>///<returns></returns>public static CryptoStream AES_DecryptStream(FileStream fs, string decryptKey){decryptKey = GetSubString(decryptKey, 32, "");decryptKey = decryptKey.PadRight(32, '');RijndaelManaged rijndaelProvider = new RijndaelManaged();rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);rijndaelProvider.IV = Keys;ICryptoTransform Decrypto = rijndaelProvider.CreateDecryptor();CryptoStream cytptostreamDecr = new CryptoStream(fs, Decrypto, CryptoStreamMode.Read);return cytptostreamDecr;}///<summary>///对指定⽂件加密///</summary>///<param name="InputFile"></param>///<param name="OutputFile"></param>///<returns></returns>public static bool AES_EncryptFile(string InputFile, string OutputFile){try{string decryptKey = "";FileStream fr = new FileStream(InputFile, FileMode.Open);FileStream fren = new FileStream(OutputFile, FileMode.Create);CryptoStream Enfr = AES_EncryptStrream(fren, decryptKey);byte[] bytearrayinput = new byte[fr.Length];fr.Read(bytearrayinput, 0, bytearrayinput.Length);Enfr.Write(bytearrayinput, 0, bytearrayinput.Length);Enfr.Close();fr.Close();fren.Close();}catch{//⽂件异常return false;}return true;}///<summary>///对指定的⽂件解压缩///</summary>///<param name="InputFile"></param>///<param name="OutputFile"></param>///<returns></returns>public static bool AES_DecryptFile(string InputFile, string OutputFile){try{string decryptKey = "";FileStream fr = new FileStream(InputFile, FileMode.Open);FileStream frde = new FileStream(OutputFile, FileMode.Create);CryptoStream Defr = AES_DecryptStream(fr, decryptKey);byte[] bytearrayoutput = new byte[1024];int m_count = 0;do{m_count = Defr.Read(bytearrayoutput, 0, bytearrayoutput.Length);frde.Write(bytearrayoutput, 0, m_count);if (m_count < bytearrayoutput.Length)break;} while (true);Defr.Close();fr.Close();frde.Close();}catch{//⽂件异常return false;}return true;}#endregion#region Base64加密解密///<summary>/// Base64是⼀種使⽤64基的位置計數法。

异或加密算法

异或加密算法

异或加密算法异或加密是⼀种很简单的加密算法,⽆论是原理还是操作性上,都不具备任何难度,所以,在做⼀些简单的加密时,被⼴为采⽤。

但因为很简答,破解起来也很容易,所以对于更加私密的信息,不要⽤这种⽅法加密。

下⾯我们简单地介绍⼀下异或的运算:数学运算符为XOR(exclusive OR),在计算机中通常⽤"^"的符号表⽰(在英⽂模式下,按住shift键+键盘上⽅的数字6)在⼆进制中:1 XOR 0=10 XOR 1=11 XOR 1=00 XOR 0=0可以看出若两个数相同取0,不同取1。

例:运算11001 ^ 01011=10010⽤其他进制表⽰的数做异或运算时,则应先将他们化为⼆进制的数,再做运算。

(不⾜的位在前边填0补齐)例:计算6^3=110^011=101*******************************************************异或运算具有可逆性。

即:若a^b=c,则有b^c=a (a,b,c分别表⽰0或1)利⽤前⾯的异或运算规则,我们就其中之⼀分析:1 XOR 0=1 则 0 XOR 1=1原理:根据异或的运算规则,相同为0,不同为1;若两个数a,b相同,a=b,则⽤任意⼀个数与0做异或时,即得到这个数本⾝,也就是另⼀个数;应⽤ 1 XOR 0 = 1 , 0 XOR 0= 0 这两个运算规则(相当于取这个数)。

若两个数a,b不同,a=~b,则⽤任意⼀个数与1做异或时,即得到这个数的相反,也就是另⼀个数应⽤ 1 XOR 1 = 0 , 0 XOR 1 = 1 这两个运算规则(相当于对这个数取反)。

**********************************************************我们不妨对异或的可逆性进⾏推⼴,对任意的两串⼆进制数做异或,得到的结果,再与其中任意⼀串⼆进制数做异或,得到另⼀串⼆进制数。

即a^b=c , 则 b^c=a.(a,b,c分别表⽰⼀串⼆进制数)与上⾯的公式形式上是相同的。

rsa加密解密算法C语言代码

rsa加密解密算法C语言代码

#include<stdio.h>#include<string.h>#include <stdlib.h>#include <time.h>#include <math.h>#include <malloc.h>#define MAX 100#define LEN sizeof(struct slink)void sub(int a[MAX],int b[MAX] ,int c[MAX] );struct slink{int bignum[MAX];/*bignum[98]用来标记正负号,1正,0负bignum[99]来标记实际长度*/struct slink *next;};/*/--------------------------------------自己建立的大数运算库-------------------------------------*/void print( int a[MAX] ){int i;for(i=0;i<a[99];i++)printf("%d",a[a[99]-i-1]);printf("\n\n");return;}int cmp(int a1[MAX],int a2[MAX]){ int l1, l2;int i;l1=a1[99];l2=a2[99];if (l1>l2)return 1;if (l1<l2)return -1;for(i=(l1-1);i>=0;i--){if (a1[i]>a2[i])return 1 ;if (a1[i]<a2[i])return -1;}return 0;}void mov(int a[MAX],int *b){int j;for(j=0;j<MAX;j++)b[j]=a[j];return ;}void mul(int a1[MAX],int a2[MAX],int *c) {int i,j;int y;int x;int z;int w;int l1, l2;l1=a1[MAX-1];l2=a2[MAX-1];if (a1[MAX-2]=='-'&& a2[MAX-2]=='-') c[MAX-2]=0;else if (a1[MAX-2]=='-')c[MAX-2]='-';else if (a2[MAX-2]=='-')c[MAX-2]='-';for(i=0;i<l1;i++){for(j=0;j<l2;j++){x=a1[i]*a2[j];y=x/10;z=x%10;w=i+j;c[w]=c[w]+z;c[w+1]=c[w+1]+y+c[w]/10;c[w]=c[w]%10;}}w=l1+l2;if(c[w-1]==0)w=w-1;c[MAX-1]=w;return;}void add(int a1[MAX],int a2[MAX],int *c) {int i,l1,l2;int len,temp[MAX];int k=0;l1=a1[MAX-1];l2=a2[MAX-1];if((a1[MAX-2]=='-')&&(a2[MAX-2]=='-')) {c[MAX-2]='-';}else if (a1[MAX-2]=='-'){mov(a1,temp);temp[MAX-2]=0;sub(a2,temp,c);return;}else if (a2[MAX-2]=='-'){mov(a2,temp);temp[98]=0;sub(a1,temp,c);return;}if(l1<l2)len=l1;else len=l2;for(i=0;i<len;i++){c[i]=(a1[i]+a2[i]+k)%10;k=(a1[i]+a2[i]+k)/10;}if(l1>len){for(i=len;i<l1;i++){c[i]=(a1[i]+k)%10;k=(a1[i]+k)/10;}if(k!=0){c[l1]=k;len=l1+1;}else len=l1;}else{for(i=len;i<l2;i++){c[i]=(a2[i]+k)%10;k=(a2[i]+k)/10;}if(k!=0){c[l2]=k;len=l2+1;}else len=l2;}c[99]=len;return;}void sub(int a1[MAX],int a2[MAX],int *c) {int i,l1,l2;int len,t1[MAX],t2[MAX];int k=0;l1=a1[MAX-1];l2=a2[MAX-1];if ((a1[MAX-2]=='-') && (a2[MAX-2]=='-')) {mov(a1,t1);mov(a2,t2);t1[MAX-2]=0;t2[MAX-2]=0;sub(t2,t1,c);return;}else if( a2[MAX-2]=='-'){mov(a2,t2);t2[MAX-2]=0;add(a1,t2,c);return;}else if (a1[MAX-2]=='-'){mov(a2,t2);t2[MAX-2]='-';add(a1,t2,c);return;}if(cmp(a1,a2)==1){len=l2;for(i=0;i<len;i++){if ((a1[i]-k-a2[i])<0){c[i]=(a1[i]-a2[i]-k+10)%10;k=1;}else{c[i]=(a1[i]-a2[i]-k)%10;k=0;}}for(i=len;i<l1;i++){if ((a1[i]-k)<0){c[i]=(a1[i]-k+10)%10;k=1;}else{c[i]=(a1[i]-k)%10;k=0;}}if(c[l1-1]==0)/*使得数组C中的前面所以0字符不显示了,如1000-20=0980--->显示为980了*/{len=l1-1;i=2;while (c[l1-i]==0)/*111456-111450=00006,消除0后变成了6;*/{len=l1-i;i++;}}else{len=l1;}}elseif(cmp(a1,a2)==(-1)){c[MAX-2]='-';len=l1;for(i=0;i<len;i++){if ((a2[i]-k-a1[i])<0){c[i]=(a2[i]-a1[i]-k+10)%10;k=1;}else{c[i]=(a2[i]-a1[i]-k)%10;k=0;}}for(i=len;i<l2;i++){if ((a2[i]-k)<0){c[i]=(a2[i]-k+10)%10;k=1;}else{c[i]=(a2[i]-k)%10;k=0;}}if(c[l2-1]==0){len=l2-1;i=2;while (c[l1-i]==0){len=l1-i;i++;}}else len=l2;}else if(cmp(a1,a2)==0){len=1;c[len-1]=0;}c[MAX-1]=len;return;}void mod(int a[MAX],int b[MAX],int *c)/*/c=a mod b//注意:经检验知道此处A和C的数组都改变了。

异或加密

异或加密
mov [ebx],eax 的完整形式是 MOV DWORD PTR DS:[EBX],EAX
XOR DWORD PTR DS:[EBX],11111111 不能写成 xor [ebx],11111111 要把DWORD型写上,否则提示请自定操作数大小
xor eax,11111111 是将eax和11111111进行异或对比结果传递回eax
popad
xor eax,11111111 异或运算并结果传递到eax、其中11111111为加密因子
mov [ebx],eax 传回已经加密的内容到ebx地址处
add ebx,4 加密地址向后4位
异或加密
总结:By Monter
异或加密原理:
a xor b的运算方法:将a,b 转化为2进制数,再进行对比,每个数位上的0或1如果相同,那么结果就取0,如果不同就取1,将得到的结果转化为原来进制的数,就是结果。
注:
mov eax,[ebx] 的完整形式是 MOV EAX,DWORD PTR DS:[EBX]
一次性单字节加密方式:
pushad
mov ebx,加密起始地址
mov ecx,加密字节大小 则循环次数
xor byte ptr ds:[ebx],33 按字节进行异或运算,加密后传回已加密内容
inc ebx ebx自加一,相当ebx+=1
简写:
pusha
mov ebx,加密起始地址
mov ecx,加密次数
XOR DWORD PTR DS:[EBX],11111111 异或加密后直接传回已经加密的内容
add ebx,4
loopd 加密代码地址
popad

des加密解密算法以及python代码实现

des加密解密算法以及python代码实现

des加密解密算法以及python代码实现DES加密解密算法是一种对称加密算法,它将明文分成固定长度的块,然后使用一个密钥进行加密和解密。

在Python中,我们可以使用pycryptodome库来实现DES加密解密算法。

首先,我们需要安装pycryptodome库。

可以使用以下命令在终端或命令提示符中安装:```shellpip install pycryptodome```接下来,我们可以使用以下代码实现DES加密和解密:```pythonfrom Crypto.Cipher import DESimport binascii# 定义密钥和明文key = b'abcdefgh'plaintext = b'Hello, world!'# 创建DES对象并设置密钥des = DES.new(key, DES.MODE_ECB)# 加密明文ciphertext = des.encrypt(plaintext)print('加密后的密文:', binascii.hexlify(ciphertext))# 解密密文decrypted_plaintext = des.decrypt(ciphertext)print('解密后的明文:', decrypted_plaintext)```在上面的代码中,我们首先定义了密钥和明文。

然后,我们创建了一个DES对象并设置了密钥。

接下来,我们使用DES对象的encrypt 方法对明文进行加密,得到密文。

最后,我们使用DES对象的decrypt 方法对密文进行解密,得到解密后的明文。

需要注意的是,上面的代码只是一种简单的实现方式,实际上DES算法的实现过程要比这复杂得多。

此外,DES算法已经被认为是不安全的,因为它使用的密钥长度只有56位,容易被暴力破解。

在实际应用中,建议使用更安全的加密算法,如AES算法。

java16进制异或方法

java16进制异或方法

java16进制异或方法【引言】在Java编程中,加密和解密算法是非常重要的技术。

16进制异或算法作为一种简单且高效的加密方法,被广泛应用于各种加密项目中。

本文将详细介绍Java中16进制异或的原理、实现及应用,帮助大家更好地理解和使用这一算法。

【Java中16进制异或的原理】16进制异或算法是基于异或运算的一种加密方法。

异或运算的规则是:0异或0等于0,1异或0等于1,1异或1等于0。

16进制异或则是将输入字符串按字节转换为16进制数,然后对每个16进制数进行异或操作。

【16进制异或算法的实现】在Java中,我们可以通过以下步骤实现16进制异或算法:1.将输入字符串转换为字节数组。

2.对字节数组中的每个字节,将其转换为对应的16进制字符串。

3.对每个16进制字符串进行异或操作。

4.将异或结果转换回字节数组。

5.将字节数组转换为16进制字符串,即为加密后的结果。

以下是一个简单的Java实现:```javapublic class HexXor {public static void main(String[] args) {String input = "Hello, World!";String encrypted = encrypt(input);System.out.println("原始字符串:" + input);System.out.println("加密后字符串:" + encrypted);}public static String encrypt(String input) {byte[] bytes = input.getBytes();StringBuilder sb = new StringBuilder();for (byte b : bytes) {sb.append(String.format("%02x", b ^ 0xff));}return sb.toString();}}```【实例演示】以上代码中,我们定义了一个`encrypt`方法用于加密输入字符串。

VB利用异或运算加密文件

VB利用异或运算加密文件

VB利用异或运算加密文件VB利用异或运算加密文件'----------------------------------------------------------------------- '作者:hellostory'日期:2011-05-26'函数名称:XOR_Encrypt'函数说明:使用异或运算加密文件(可加密大部分文件)'参数说明:key - 密钥' fileName - 普通文件名,' encryptFileName - 加密后的文件名'返回值:true - 成功,false - 失败'-----------------------------------------------------------------------Private Function XOR_Encrypt(key As Integer, fileName As String, encryptFileName As String) As BooleanOn Error GoTo errHandlerDim inputFileNo As IntegerDim fileBytes() As ByteDim length As LongXOR_Encrypt = False'打开文件并保存在二进制数组中inputFileNo = FreeFileOpen fileName For Binary As #inputFileNolength = LOF(inputFileNo)If length = 0 ThenMsgBox "退出加密:文件内容为空!", vbInformation, "提示"Exit FunctionEnd IfReDim fileBytes(length - 1) As ByteGet inputFileNo, , fileBytes()Close #inputFileNo'将该二进制数组进行异或加密Dim i As LongFor i = LBound(fileBytes) To UBound(fileBytes)fileBytes(i) = fileBytes(i) Xor keyNext'将异或加密后的二进制数组保存在新的文件中Dim outputFileNo As IntegeroutputFileNo = FreeFileOpen encryptFileName For Binary As #outputFileNo Put outputFileNo, , fileBytesClose #outputFileNoXOR_Encrypt = TrueerrHandler:If Err.Number ThenMsgBox "加密过程中出错:" & Err.Description, vbCritical, "错误"XOR_Encrypt = FalseResume NextEnd IfEnd Function 摘自hellostory的专栏。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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;
#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);/*得到密码*/
运用异或的方法进行的加密解密算法可对文件进行基于字符变形的加密/解密。编写程序,程序运行需要口令,口令存放在一个文件中,为了避免口令文件被阅读,不能以明文形式存放,利用(1)的思路,生成一个口令密文文件,可以修改口令。
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
printf("Out-file:\n");
gets(out_fname);/*得到加密后你要的文件名*/
dofile(in_fname,pwd,out_fname);
}
else{/*如果命令行参数正确,便直接运行程序*/
strcpy(in_fname,argv[1]);
strcpy(pwd,argv[2]);
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);
}
f闭目标文件*/
}
/*程序结束*/
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){
相关文档
最新文档