C语言字符串加密解密程序
- 格式:doc
- 大小:43.50 KB
- 文档页数:2
rsa加密解密算法c语言程序RSA加密解密算法是一种公钥加密算法,发明于1977年,基于两个大质数的乘积难分解性,能够对短文本进行加解密。
以下是RSA加密解密算法的C语言程序。
一、密钥生成首先定义了一个结构体存储RSA密钥,该结构体包含三个元素:n、e和d。
- n = p * q,其中p和q为大质数;- e为与(p - 1) * (q - 1)互质的自然数,一般选取65537;- d为e模(p - 1) * (q - 1)的逆元素,即满足e * d ≡ 1 (mod (p - 1) * (q - 1)))的自然数。
generateRSAKey函数通过调用randomPrime函数生成两个大质数p和q,再通过Euclidean函数计算(p - 1) * (q - 1)的值phi,最后继续使用extendedEuclidean函数计算d的值,最终将生成的密钥存储在RSAKey结构体中。
```c#include <stdio.h>#include <stdlib.h>#include <time.h>#include <math.h>#define k 1024 // 密钥长度typedef struct {unsigned long long n;unsigned long long e;unsigned long long d;} RSAKey;unsigned long long randomPrime(unsigned long long n);unsigned long long gcd(unsigned long long a, unsigned long long b);unsigned long long Euclidean(unsigned long long a, unsigned long long b);RSAKey generateRSAKey();// 生成一个小于n的随机质数unsigned long long randomPrime(unsigned long long n) {unsigned long long p;do {p = rand() % n;while (!(p & 1)) // 确保p为奇数p = rand() % n;} while (gcd(p, n) != 1); // 确保p和n互质return p;}二、加密和解密下面定义了两个函数:encrypt和decrypt,其中encrypt函数用于将明文转换为密文,decrypt函数用于将密文转换为明文。
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;}```以上程序演示了凯撒密码的加密与解密过程,通过指定偏移量实现对消息的加密与解密。
c语言文本加密解密课程设计一、课程目标知识目标:1. 让学生掌握C语言中字符类型及其运算,特别是字符与ASCII码之间的关系。
2. 使学生理解文本加密解密的基本原理,包括对称加密算法中异或运算的应用。
3. 引导学生掌握使用C语言进行简单文本加密解密程序的编写。
技能目标:1. 培养学生运用C语言进行字符处理的能力,包括字符串的读取、修改和输出。
2. 培养学生将理论知识应用到实际编程中,解决文本加密解密问题的能力。
3. 提高学生的逻辑思维能力和问题解决能力,通过编程实践,学会调试和优化程序。
情感态度价值观目标:1. 培养学生对编程的兴趣和热情,增强学习C语言的自信心。
2. 引导学生认识到信息安全的重要性,提高网络安全意识。
3. 培养学生的团队合作精神,学会在编程过程中互相帮助、共同进步。
分析课程性质、学生特点和教学要求,本课程目标旨在使学生在掌握C语言基础知识和技能的基础上,通过学习文本加密解密,将理论知识与实践相结合,提高编程能力和信息安全意识。
课程目标具体、可衡量,便于后续教学设计和评估。
二、教学内容1. C语言基础知识回顾:字符类型及其ASCII码表示,字符串处理基础。
2. 文本加密解密原理:介绍对称加密基本概念,重点讲解异或运算在文本加密解密中的应用。
3. 编程实践:- 简单文本加密程序设计:使用C语言实现字符异或加密。
- 简单文本解密程序设计:使用C语言实现字符异或解密。
4. 教学案例分析与讨论:分析教材中相关的案例,讲解加密解密程序的设计思路和实现步骤。
5. 课堂练习:设计具有实际意义的加密解密任务,让学生动手实践,巩固所学知识。
教学内容安排和进度:第一课时:C语言基础知识回顾,文本加密解密原理介绍。
第二课时:编程实践——简单文本加密程序设计。
第三课时:编程实践——简单文本解密程序设计。
第四课时:教学案例分析与讨论,课堂练习。
教学内容与教材关联性:1. C语言基础知识:参考教材第1章至第3章内容。
C语言字符串加密和解密算法在本实例中要求设计一个加密和解密算法。
在对一个指定的字符串加密之后,利用解密函数能够对密文解密,显示明文信息。
加密的方式是将字符串中每个字符加上它在字符串中的位置和一个偏移值5。
以字符串“mrsoft”为例,第一个字符“m”在字符串中的位置为0,那么它对应的密文是“'m'+0+5",即r。
算法思想在main() 函数中使用while 语句设计一个无限循环,并定义两个字符数组,用来保存,明文和密文字符串,在首次循环中要求用户输入字符串,进行将明文加密成密文的操作,之后的操作则是根据用户输入的命令字符进行判断,输入1 加密新的明文,输入2 对刚加密的密文进行解密,输入3 退出系统。
程序代码1.#include<stdio.h>2.#include<string.h>3.int main()4.{5.int result=1;6.int i;7.int count=0;8.char Text[128]={'\0'};9.char cryptograph[128]={'\0'};10.while(1)11.{12.if(result==1)13.{14.printf("请输入要加密的明文:\n");15.scanf("%s",&Text);16. count=strlen(Text);17.for(i=0;i<count;i++)18.{19. cryptograph[i]=Text[i]+i+5;20.}21. cryptograph[i]='\0';22.printf("加密后的密文是:%s\n",cryptograph);23.}24.else if(result==2)25.{26. count=strlen(Text);27.for(i=0;i<count;i++)28.{29. Text[i]=cryptograph[i]-i-5;30.}31. Text[i]='\0';32.printf("解密后的明文是:%s\n",Text);33.}34.else if(result==3)35.{36.break;37.}38.else39.{40.printf("请输入正确的命令符:\n");41.}42.printf("输入1加密新的明文,输入2对刚加密的密文进行解密,输入3退出系统:\n");43.printf("请输入命令符:\n");44.scanf("%d",&result);45.}46.return0;47.}调试运行结果本实例中,输入了I love Xichang College 字符串作为例证,因此输出是多个加密后的字符串,结果如下所示:。
在C语言中,实现一个简单的凯撒密码字符串加密的程序可能如下:```c#include <stdio.h>#include <string.h>void caesar_encrypt(char *str, int shift) {int len = strlen(str);for (int i = 0; i < len; i++) {if (str[i] >= 'a' && str[i] <= 'z') {str[i] = ((str[i] - 'a' + shift) % 26) + 'a';} else if (str[i] >= 'A' && str[i] <= 'Z') {str[i] = ((str[i] - 'A' + shift) % 26) + 'A';}}}int main() {char str[100];printf("请输入一个字符串: ");fgets(str, sizeof(str), stdin); // 从标准输入读取字符串caesar_encrypt(str, 3); // 对字符串进行凯撒密码加密,偏移量为3printf("加密后的字符串: %s\n", str);return 0;}```这个程序首先定义了一个`caesar_encrypt`函数,该函数接收一个字符串和一个偏移量作为参数,然后对字符串中的每个字符进行凯撒密码加密。
在主函数中,我们读取用户输入的字符串,然后调用`caesar_encrypt`函数进行加密,并打印出加密后的字符串。
这个程序只处理了小写字母和大写字母,对于其他字符(如数字、标点符号等),它们将保持不变。
实现字符串的加密与解密//实现字符串的加密与解密//加密⽅式:将字符串中每个字符加上它在字符中的位置和⼀个偏移量 5//列如:zhnglie中,第⼀个字符z在字符中的位置为0,那么对应密⽂是'm'+0+51 #include<stdio.h>2 #include<stdlib.h>3 #include<string.h>45#define KEY 5 //偏移量或者是密钥以字符的⽅式来偏移不要越界6//⽆符号char 型 0-25578/**9 *加密传⼊的字符串10 *参数1:要加密的字符串11 *返回值:返回值加密后的字符串12*/131415//原函数16char * encrypt(char []); //加密1718char * dencrypt(char []); //解密1920int main()21 {2223char password[50] = "123456";2425 encrypt(password);26 printf("加密后的字符串为:%s\n",password);272829 dencrypt(password);30 printf("解密后的字符串为:%s\n",password);313233return0;34 }3536//加密37char * encrypt(char password[])38 {3940int i = 0;41int count = strlen(password); //字符串的长度42for(i = 0;i <strlen(password); i++)43 {44////加密⽅式:将字符串中每个字符加上它在字符中的位置和⼀个偏移量 545 password[i] = password[i] + i + KEY;4647 }48return password;4950//字符串最后的\0是否需要替换?----不需要51 }5253//解密54char * dencrypt(char password[])55 {5657int i = 0;58int count = strlen(password); //字符串的长度59for(i = 0;i <strlen(password); i++)60 {61////加密⽅式:将字符串中每个字符加上它在字符中的位置和⼀个偏移量 562 password[i] = password[i] - i - KEY;6364 }65return password;6667//字符串最后的\0是否需要替换?----不需要68 }。
⽤C语⾔简单加密解密使⽤char表⽰的字符型数据,在本质上与我们前⾯介绍的整型数据并⽆太⼤的区别,只是char类型占⽤的内存字节数更⼩,能够表⽰的数据范围更⼩⽽已。
在使⽤上,char被专门⽤来表⽰C语⾔的字符集中的各种字符,不要把它当成⼀个整型数据类型来使⽤。
对于字符类型,我们常常利⽤它来处理字符串中的单个字符或者是实现⼀些字符游戏。
例如,我们可以对字符串中的单个字符进⾏运算,实现字符串的简单加密:#include <stdio.h>#include <string.h> // strlen()函数所在的头⽂件#include <ctype.h> // isalpha()函数所在的头⽂件int main(){// 定义⼀个明⽂字符串char msg[] = "This is C program!";int i = 0 ;// 逐个遍历字符串中的字符,对其进⾏处理for(i=0; i<strlen(msg); i++){// 获得字符串中的当前字符char cur = msg[i];// 判断当前字符是否是字母字符if(isalpha(cur))// 对字母字符进⾏简单加密处理,然后重新写回字符串msg[i] = cur +1;}// 输出加密后的字符串printf("the encrypted message is: %s\n",msg);//解码for(i=0; i<strlen(msg); i++){char c =msg[i];if(isalpha(c)){msg[i] = c - 1;}}printf("the decrypted message is: %s\n",msg);return0;}这样实现了C语⾔的简单加密和解密!。
1、方法一 (不可逆)public string EncryptPassword(string PasswordString,string PasswordFormat ){string encryptPassword = null;if (PasswordFormat="SHA1"){encryptPassword=FormsAuthortication.HashPasswordForStoringInConfigFile(PasswordS tring,"SHA1");}elseif (PasswordFormat="MD5"){ encryptPassword=FormsAuthortication.HashPasswordForStoringInConfigFile(Passwor dString,"MD5");}return encryptPassword ;}2、方法二 (可逆)public interface IBindesh{string encode(string str);string decode(string str);}public class EncryptionDecryption : IBindesh{public string encode(string str){string htext = "";for ( int i = 0; i < str.Length; i++){htext = htext + (char) (str[i] + 10 - 1 * 2);}return htext;public string decode(string str){string dtext = "";for ( int i=0; i < str.Length; i++){dtext = dtext + (char) (str[i] - 10 + 1*2);}return dtext;}3、方法三 (可逆)const string KEY_64 = "VavicApp";//注意了,是8个字符,64位const string IV_64 = "VavicApp";public string Encode(string data){byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();int i = cryptoProvider.KeySize;MemoryStream ms = new MemoryStream();CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey,byIV), CryptoStreamMode.Write);StreamWriter sw = new StreamWriter(cst);sw.Write(data);sw.Flush();cst.FlushFinalBlock();sw.Flush();return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);public string Decode(string data){byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);byte[] byEnc;try{byEnc = Convert.FromBase64String(data);}catch{return null;}DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();MemoryStream ms = new MemoryStream(byEnc);CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey,byIV), CryptoStreamMode.Read);StreamReader sr = new StreamReader(cst);return sr.ReadToEnd();}4、MD5不可逆加密(32位加密)public string GetMD5(string s, string _input_charset){/**//**//**//// <summary>/// 与ASP兼容的MD5加密算法/// </summary>MD5 md5 = new MD5CryptoServiceProvider();byte[] t = puteHash(Encoding.GetEncoding(_input_charset).GetBytes(s));StringBuilder sb = new StringBuilder(32);for (int i = 0; i < t.Length; i++){sb.Append(t[i].ToString("x").PadLeft(2, '0'));}return sb.ToString();}(16位加密)public static string GetMd5Str(string ConvertString){MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();string t2 =BitConverter.ToString(puteHash(UTF8Encoding.Default.GetBytes(ConvertStrin g)), 4, 8);t2 = t2.Replace("-", "");return t2;}5、加解文本文件//加密文件private static void EncryptData(String inName, String outName, byte[] desKey, byte[]desIV){//Create the file streams to handle the input and output files.FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); FileStream fout = new FileStream(outName, 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 ata time.DES des = new DESCryptoServiceProvider();CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV),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();}//解密文件private static void DecryptData(String inName, String outName, byte[] desKey, byte[]desIV){//Create the file streams to handle the input and output files.FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); FileStream fout = new FileStream(outName, 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(desKey, desIV),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();}6、using System;using System.Collections.Generic;using System.Text;using System.Security.Cryptography;using System.IO;namespace Component{public class Security{public Security(){}//默认密钥向量private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };/**//**//**//**//**//**//**//// <summary>/// DES加密字符串/// </summary>/// <param name="encryptString">待加密的字符串</param>/// <param name="encryptKey">加密密钥,要求为8位</param>/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>public static string EncryptDES(string encryptString, string encryptKey){try{byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));byte[] rgbIV = Keys;byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream();CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey,rgbIV), CryptoStreamMode.Write);cStream.Write(inputByteArray, 0, inputByteArray.Length);cStream.FlushFinalBlock();return Convert.ToBase64String(mStream.ToArray());}catch{return encryptString;}}/**//**//**//**//**//**//**//// <summary>/// DES解密字符串/// </summary>/// <param name="decryptString">待解密的字符串</param>/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param> /// <returns>解密成功返回解密后的字符串,失败返源串</returns>public static string DecryptDES(string decryptString, string decryptKey) {try{byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);byte[] rgbIV = Keys;byte[] inputByteArray = Convert.FromBase64String(decryptString); DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream();CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey,rgbIV), CryptoStreamMode.Write);cStream.Write(inputByteArray, 0, inputByteArray.Length);cStream.FlushFinalBlock();return Encoding.UTF8.GetString(mStream.ToArray()); }catch{return decryptString;}}}}。
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`位实现解密。
aes算法c语言实现AES(Advanced Encryption Standard)是一种广泛应用于数据加密的算法。
以下是一个使用C语言实现的AES加密算法示例,用于对字符串进行加密和解密。
这个实现是基于ECB模式的,这是一种常用的加密模式,因为它简单且易于实现。
注意:这个实现是为了教学目的而提供的,可能不适合用于生产环境。
生产环境中的加密实现通常需要更复杂和安全的方法。
```c #include <stdio.h> #include <string.h> #include <stdint.h> #include <openssl/aes.h>void AES_encrypt(const uint8_t *key, const uint8_t*plaintext, uint8_t *ciphertext) { AES_KEY aesKey; AES_set_encrypt_key(key, 128, &aesKey);AES_encrypt(plaintext, ciphertext, &aesKey); }void AES_decrypt(const uint8_t *key, const uint8_t*ciphertext, uint8_t *plaintext) { AES_KEY aesKey; AES_set_decrypt_key(key, 128, &aesKey);AES_decrypt(ciphertext, plaintext, &aesKey); }int main() { // 定义密钥和明文/密文缓冲区uint8_t key[AES_BLOCK_SIZE]; // AES_BLOCK_SIZE是AES算法的块大小,通常是16字节(128位) uint8_tplaintext[AES_BLOCK_SIZE], ciphertext[AES_BLOCK_SIZE];// 填充密钥和明文/密文缓冲区 // 这里省略了填充代码,因为在实际应用中,你应该使用合适的填充方案来保护数据的完整性。