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);