A. c语言文件加密和解密
c语言文件加密和解密方法如下:
1、首先打开VC++6.0;
voidDecryptFile(FILE*sfp,FILE*dfp,charpwd)
{
charch;
while((ch=fgetc(sfp))!=EOF)
{
if((ch>='a')&&(ch<='z'))
{
ch=ch^pwd;
ch=(ch-'a'+25)%26+'a';
}
if((ch>='A')&&(ch<='Z'))
{
ch=ch^pwd;
ch=(ch-'A'+25)%26+'A';
}
fputc(ch,dfp);
}
}
输出函数,输出文件内容
voidOutputFile(FILE*fp)
{
charch;
while((ch=fgetc(fp))!=EOF)
putchar(ch);
}
主函数,主要调用这几个函数
intmain()
{
/*用户输入的要加密的文件名*/
charsfilename[20];
/*用户输入加密后保存的文件名*/
chardfilename[20];
/*用来保存密码字符*/
charpwd;
FILE*sfp,*dfp;
printf(":
");
/*得到要加密的文件名*/
gets(sfilename);
/*得到加密后你要的文件名*/
printf(":
");
gets(dfilename);
/*得到加密字符*/
printf("PleaseinputyourPassword:
");
//scanf("%c",&pwd);
pwd=getch();
/*屏幕以*来表示输入的加密字符*/
printf("*
");
/*以只读方式打开要加密的文件*/
if((sfp=fopen(sfilename,"r"))==0)
{
printf("Can'topenthefile:%s
",sfilename);
exit(0);
}
/*输出要加密的文件*/
printf(":
");
OutputFile(sfp);
/*建立加密后的文件*/
if((dfp=fopen(dfilename,"w+"))==0)
{
printf("Can'topenorcreatethefile:%s
",dfilename);
//exit(0);
}
/*文件加密*/
fseek(sfp,0L,SEEK_SET);
EncryptFile(sfp,dfp,pwd);
printf("
Encryptedthefilesuccessfully!
");
/*输出加密后的文件*/
printf(":
");
fseek(dfp,0L,SEEK_SET);
OutputFile(dfp);
fclose(sfp);
fclose(dfp);
getch();
return0;
}
B. 求用c语言写的文件加密解密代码
/*给文件加密的技术很多,其中又分为不同等级,以适合不同场合的需要.
这里给出最简单的文件加密技术,即采用文件逐字节与密码异或方式对
文件进行加密,当解密时,只需再运行一遍加密程序即可.
*/
#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); /*把密码重复写到fp2中,而不是
只写一次*/
}
fclose(fp1);/*关闭源文件*/
fclose(fp2);/*关闭目标文件*/
getch();
}
/*程序结束*/
C. VB 加密与解密的程序代码
加密:
PrivateFunction JiaMi(ByVal varPass As String) As String '参数varPass是需要加密的文本内容
Dim varJiaMi As String * 20
Dim varTmp As Double
Dim strJiaMi As String
Dim I
For I = 1 To Len(varPass)
varTmp = AscW(Mid$(varPass, I, 1))
varJiaMi = Str$(((((varTmp * 1.5) / 5.6) * 2.7) * I))
strJiaMi = strJiaMi & varJiaMi
NextI
JiaMi = strJiaMi
EndFunction
解密函数:
PrivateFunction JieMi(ByVal varPass As String) As String '参数varPass是需要解密的密文内容
Dim varReturn As String * 20
Dim varConvert As Double
Dim varFinalPass As String
Dim varKey As Integer
Dim varPasslenth As Long
varPasslenth = Len(varPass)
For I = 1 To varPasslenth / 20
varReturn = Mid(varPass, (I - 1) * 20 + 1, 20)
varConvert = Val(Trim(varReturn))
varConvert = ((((varConvert / 1.5) * 5.6) / 2.7) / I)
varFinalPass = varFinalPass & ChrW(Val(varConvert))
NextI
JieMi = varFinalPass
EndFunction
注意事项
编写加密程序,将用户输入的一个英文句子加密为加密字符串,然后输出加密字符串。假设句子长度不超过100个字符。
根据给定的句子加密函数原型SentenceEncoding,编写函数SentenceEncoding调用给定的字符加密函数CharEncoding完成句子加密。
然后,编写主程序提示用户输入英文句子,然后调用函数SentenceEncoding对句子加密,最后输出加密后的句子。
字符加密规则为大写字母和小写字母均加密为其补码, 我们定义ASCII码值相加为’A’+’Z’即155的两个大写字母互为补码,ASCII码值相加为’a’+’z’即219的两个小写字母互为补码。
空格用@代替,句号以#代替,其它字符用句点代替。
函数原型:
void SentenceEncoding(char *soure,char *code);
功能:对待加密字符串source加密后保存加密字符串到code.
参数:char *soure,指向待加密句子的字符串指针;
char *code 指向加密字符串的字符串指针;
字符加密函数代码。
D. 关于用C语言对文件进行加密和解密
ch=ch^*(pwd+i); //对读取的一个字符,进行异或
重点是这,,,,,,就是使用密码,对源文件逐byte异或、
if(i>9){
i=0;
}
密码也循环使用。
~~~~~~~~~~~~
E. java加密解密代码
package com.cube.limail.util;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;/**
* 加密解密类
*/
public class Eryptogram
{
private static String Algorithm ="DES";
private String key="CB7A92E3D3491964";
//定义 加密算法,可用 DES,DESede,Blowfish
static boolean debug = false ;
/**
* 构造子注解.
*/
public Eryptogram ()
{
} /**
* 生成密钥
* @return byte[] 返回生成的密钥
* @throws exception 扔出异常.
*/
public static byte [] getSecretKey () throws Exception
{
KeyGenerator keygen = KeyGenerator.getInstance (Algorithm );
SecretKey deskey = keygen.generateKey ();
System.out.println ("生成密钥:"+bytesToHexString (deskey.getEncoded ()));
if (debug ) System.out.println ("生成密钥:"+bytesToHexString (deskey.getEncoded ()));
return deskey.getEncoded ();
} /**
* 将指定的数据根据提供的密钥进行加密
* @param input 需要加密的数据
* @param key 密钥
* @return byte[] 加密后的数据
* @throws Exception
*/
public static byte [] encryptData (byte [] input ,byte [] key ) throws Exception
{
SecretKey deskey = new javax.crypto.spec.SecretKeySpec (key ,Algorithm );
if (debug )
{
System.out.println ("加密前的二进串:"+byte2hex (input ));
System.out.println ("加密前的字符串:"+new String (input ));
} Cipher c1 = Cipher.getInstance (Algorithm );
c1.init (Cipher.ENCRYPT_MODE ,deskey );
byte [] cipherByte =c1.doFinal (input );
if (debug ) System.out.println ("加密后的二进串:"+byte2hex (cipherByte ));
return cipherByte ;
} /**
* 将给定的已加密的数据通过指定的密钥进行解密
* @param input 待解密的数据
* @param key 密钥
* @return byte[] 解密后的数据
* @throws Exception
*/
public static byte [] decryptData (byte [] input ,byte [] key ) throws Exception
{
SecretKey deskey = new javax.crypto.spec.SecretKeySpec (key ,Algorithm );
if (debug ) System.out.println ("解密前的信息:"+byte2hex (input ));
Cipher c1 = Cipher.getInstance (Algorithm );
c1.init (Cipher.DECRYPT_MODE ,deskey );
byte [] clearByte =c1.doFinal (input );
if (debug )
{
System.out.println ("解密后的二进串:"+byte2hex (clearByte ));
System.out.println ("解密后的字符串:"+(new String (clearByte )));
} return clearByte ;
} /**
* 字节码转换成16进制字符串
* @param byte[] b 输入要转换的字节码
* @return String 返回转换后的16进制字符串
*/
public static String byte2hex (byte [] b )
{
String hs ="";
String stmp ="";
for (int n =0 ;n <b.length ;n ++)
{
stmp =(java.lang.Integer.toHexString (b [n ] & 0XFF ));
if (stmp.length ()==1 ) hs =hs +"0"+stmp ;
else hs =hs +stmp ;
if (n <b.length -1 ) hs =hs +":";
} return hs.toUpperCase ();
}
/**
* 字符串转成字节数组.
* @param hex 要转化的字符串.
* @return byte[] 返回转化后的字符串.
*/
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static byte toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}
/**
* 字节数组转成字符串.
* @param String 要转化的字符串.
* @return 返回转化后的字节数组.
*/
public static final String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
/**
* 从数据库中获取密钥.
* @param deptid 企业id.
* @return 要返回的字节数组.
* @throws Exception 可能抛出的异常.
*/
public static byte[] getSecretKey(long deptid) throws Exception {
byte[] key=null;
String value=null;
//CommDao =new CommDao();
// List list=.getRecordList("from Key k where k.deptid="+deptid);
//if(list.size()>0){
//value=((com.csc.sale.bean.Key)list.get(0)).getKey();
value = "CB7A92E3D3491964";
key=hexStringToByte(value);
//}
if (debug)
System.out.println("密钥:" + value);
return key;
}
public String encryptData2(String data) {
String en = null;
try {
byte[] key=hexStringToByte(this.key);
en = bytesToHexString(encryptData(data.getBytes(),key));
} catch (Exception e) {
e.printStackTrace();
}
return en;
}
public String decryptData2(String data) {
String de = null;
try {
byte[] key=hexStringToByte(this.key);
de = new String(decryptData(hexStringToByte(data),key));
} catch (Exception e) {
e.printStackTrace();
}
return de;
}
} 加密使用: byte[] key=Eryptogram.getSecretKey(deptid); //获得钥匙(字节数组)
byte[] tmp=Eryptogram.encryptData(password.getBytes(), key); //传入密码和钥匙,获得加密后的字节数组的密码
password=Eryptogram.bytesToHexString(tmp); //将字节数组转化为字符串,获得加密后的字符串密码解密与之差不多
F. C++文件的加密和解密代码
最简单的两种加解密方式
单字节操作 上下文无关
供参考
#include<stdio.h>
voiddo_0(FILE*fin,FILE*fout)
{
#undefKEY
#defineKEY0x37
intc;
while((c=fgetc(fin))!=EOF)
{
c^=KEY;
fputc(c,fout);
}
}
voiddo_1_0(FILE*fin,FILE*fout)
{
#undefKEY
#defineKEY0x06
intc;
while((c=fgetc(fin))!=EOF)
{
c+=KEY;
c%=256;
fputc(c,fout);
}
}
voiddo_1_1(FILE*fin,FILE*fout)
{
#undefKEY
#defineKEY0x06
intc;
while((c=fgetc(fin))!=EOF)
{
c+=256-KEY;
c%=256;
fputc(c,fout);
}
}
intmain()
{
intmode,type;
charin_file[128],out_file[128];
FILE*fp_in,*fp_out;
do
{
printf("selectrunmode:0->encrypt1->decrypt ");
scanf("%d",&mode);
}while(mode!=0&&mode!=1);
do
{
printf("selecttype:0/1 ");
scanf("%d",&type);
}while(type!=0&&type!=1);
getchar();
do
{
printf("inputfilename: ");
gets(in_file);
fp_in=fopen(in_file,"rb");
if(fp_in==NULL)
printf("cannotreadfile%s ",in_file);
}while(fp_in==NULL);
do
{
printf("outputfilename: ");
gets(out_file);
fp_out=fopen(out_file,"wb");
if(fp_out==NULL)
printf("cannotwritefile%s ",out_file);
}while(fp_out==NULL);
if(type==0)
do_0(fp_in,fp_out);
elseif(mode==0)
do_1_0(fp_in,fp_out);
elsedo_1_1(fp_in,fp_out);
fclose(fp_in);
fclose(fp_out);
return0;
}
G. 谁能提供下java中有关加密和解密的代码
publicstaticvoidmain(String[]args)throwsException{
Stringdata="itxxz";
System.out.println("字符串:itxxz");
System.err.println("加密:"+encrypt(data));
System.err.println("解密:"+decrypt(encrypt(data)));
}
运行结果:
由于代码太多,可到 itxxz.com/a/javashili/2014/1217/encrypt_decrypt.html 查看,注释也比较完整,清晰易懂
H. C#加密解密代码
做个测试,希望有所帮助。 /// <summary>
/// 加密
/// </summary>
private void button1_Click(object sender, EventArgs e)
{
string data1 = this.textBox1.Text.Trim();
if (data1.Length != 4)
{
MessageBox.Show("输入不是四位整数,请重新输入!", "提示信息");
this.textBox1.Select();
return;
}
foreach (char c in data1)
{
if (!(c >= '0' && c <= '9'))
{//如果不是整数
MessageBox.Show("输入中含有非整数,请重新输入!", "提示信息");
this.textBox1.Select();
return;
}
} int d1 = Convert.ToInt32(data1[0].ToString());
int d2 = Convert.ToInt32(data1[1].ToString());
int d3 = Convert.ToInt32(data1[2].ToString());
int d4 = Convert.ToInt32(data1[3].ToString());
int d = 0;
//加密
//每位数字用该位数字加7所得的和对10取模,所得到的数值代替该位数字
d1 = (d1 + 7) % 10;
d2 = (d2 + 7) % 10;
d3 = (d3 + 7) % 10;
d4 = (d4 + 7) % 10;
//第1位数字和第3位数字交换位置
d = d1;
d1 = d3;
d3 = d;
//第2位和第4位数字交换位置
d = d2;
d2 = d4;
d4 = d; //显示加密后的字符串
string data2 = d1.ToString() + d2.ToString() + d3.ToString() + d4.ToString();
this.textBox2.Text = data2;
} /// <summary>
/// 解密
/// </summary>
private void button2_Click(object sender, EventArgs e)
{
if (this.textBox2.Text == string.Empty)
{
MessageBox.Show("未进行加密操作!", "提示信息");
return;
}
string data2 = this.textBox2.Text.Trim();
int d1 = Convert.ToInt32(data2[0].ToString());
int d2 = Convert.ToInt32(data2[1].ToString());
int d3 = Convert.ToInt32(data2[2].ToString());
int d4 = Convert.ToInt32(data2[3].ToString());
int d = 0; //解密
//第1位数字和第3位数字交换位置
d = d1;
d1 = d3;
d3 = d;
//第2位和第4位数字交换位置
d = d2;
d2 = d4;
d4 = d;
//每位数字用该位数字加10所得的和减7,所得到的数值代替该位数字
d1 = d1 >= 7 ? d1 - 7 : (d1 + 10) - 7;
d2 = d2 >= 7 ? d2 - 7 : (d2 + 10) - 7;
d3 = d3 >= 7 ? d3 - 7 : (d3 + 10) - 7;
d4 = d4 >= 7 ? d4 - 7 : (d4 + 10) - 7;
//显示加密后的字符串
string data3 = d1.ToString() + d2.ToString() + d3.ToString() + d4.ToString();
this.textBox3.Text = data3;
}
I. c# 加密和解密代码
加密有很多中,常用的有MD5
C# md5加密(上)
string a; //加密前数据
string b; //加密后数据
b=System.Web.Security.FormsAuthentication.(a,"MD5")
using System;
using System.Security.Cryptography;
方法2
public static string GetMD5(string myString)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString);
byte[] targetData = md5.ComputeHash(fromData);
string byte2String = null;
for (int i=0; i<targetData.Length; i++)
{
byte2String += targetData[i].ToString("x");
}
return byte2String;
}
using System.Security.Cryptography;
/// <summary>
/// 给一个字符串进行MD5加密
/// </summary>
/// <param name="strText">待加密字符串</param>
/// <returns>加密后的字符串</returns>
public static string MD5Encrypt(string strText)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(strText));
return System.Text.Encoding.Default.GetString(result);
}
C# MD5加密
using System.Security.Cryptography;
private void btnOK_Click(object sender, System.EventArgs e)
{
string strConn = "server=192.168.0.51;database=chengheng;User id=sa; password=123";
if(texName.Text.Trim()=="")
{
this.RegisterStartupScript("sf","<script language='javascript'>alert('用户名不能为空');document.all('texName').focus()</script>");
return;
}
else if(texPassword.Text.Trim()=="")
{
this.RegisterStartupScript("sfs","<script language='javascript'>alert('密码不能为空');document.all('texPassword').focus()</script>");
return;
}
else
{
//将获取的密码加密与数据库中加了密的密码相比较
byte[] by = md5.ComputeHash(utf.GetBytes(texPassword.Text.Trim()));
string resultPass = System.Text.UTF8Encoding.Unicode.GetString(by);
conn.ConnectionString=strConn;
SqlCommand comm = new SqlCommand();
string name = texName.Text.Trim().ToString();
comm.CommandText="select Ruser_pwd,Ruser_nm from Ruser where Accountno = @name";
comm.Parameters.Add("@name",SqlDbType.NVarChar,40);
comm.Parameters["@name"].Value=name;
try
{
conn.Open();
comm.Connection=conn;
SqlDataReader dr=comm.ExecuteReader();
if(dr.Read())
{
//用户存在,对密码进行检查
if(dr.GetValue(0).Equals(resultPass))
{
string user_name=dr.GetValue(1).ToString();
string user_Accountno=texName.Text.Trim();
Session["logon_name"]=user_name;
Session["logon_Accountno"]=user_Accountno;
//登录成功,进行页面导向
}
else
{
this.RegisterStartupScript("wp","<script language='javascript'>alert('密码错误,请检查。')</script>");
}
}
else
{
this.RegisterStartupScript("nu","<script language=javascript>alert('用户名不存在,请检查。')</script>");
}
}
catch(Exception exec)
{
this.RegisterStartupScript("wc","<script language=javascript>alert('网络连接有异,请稍后重试。')</script>");
}
finally
{
conn.Close();
}
}
}
J. C#如何对Excel文件进行加密和解密,有没有代码可以告诉我的
用这个组件-Spire.XLS,亲测有效,支持多种加密/保护方式,实现方案:
C# Excel 文档保护
加密代码:
//初始化一个Workbook实例并加载文档
Workbookworkbook=newWorkbook();
workbook.LoadFromFile("Test.xlsx");
////使用密码保护工作薄
//workbook.Protect("123");
//密码保护工作薄,并保护工作薄结构
workbook.Protect("123",true,true);
workbook.SaveToFile("ProtectExcel.xlsx",ExcelVersion.Version2013);
解密代码:
//加载Excel文档
Workbookworkbook=newWorkbook();
workbook.LoadFromFile("Sample.xlsx");
//获取第一个工作表
Worksheetsheet=workbook.Worksheets[0];
//输入密码取消保护工作表
sheet.Unprotect("123");
//保存文档workbook.SaveToFile("Result.xlsx",ExcelVersion.Version2013);