69,371
社区成员
发帖
与我相关
我的任务
分享
#pragma comment(lib, "crypt32.lib")
#pragma comment(lib, "advapi32.lib")
#define _WIN32_WINNT 0x0400
#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>
#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
#define KEYLENGTH 0x00800000
void HandleError(char *s);
//--------------------------------------------------------------------
// These additional #define statements are required.
#define ENCRYPT_ALGORITHM CALG_RC4
#define ENCRYPT_BLOCK_SIZE 8
// Declare the function EncryptFile. The function definition
// follows main.
BOOL EncryptFile(
PCHAR szSource,
PCHAR szDestination,
PCHAR szPassword);
//--------------------------------------------------------------------
// Begin main.
void main(void) {
CHAR szSource[100];
CHAR szDestination[100];
CHAR szPassword[100];
printf("Encrypt a file. \n\n");
printf("Enter the name of the file to be encrypted: ");
scanf("%s",szSource);
printf("Enter the name of the output file: ");
scanf("%s",szDestination);
printf("Enter the password:");
scanf("%s",szPassword);
//--------------------------------------------------------------------
// Call EncryptFile to do the actual encryption.
if(EncryptFile(szSource, szDestination, szPassword)) {
printf("Encryption of the file %s was a success. \n", szSource);
printf("The encrypted data is in file %s.\n",szDestination);
} else {
HandleError("Error encrypting file!");
}
} // End of main
//--------------------------------------------------------------------
// Code for the function EncryptFile called by main.
static BOOL EncryptFile(
PCHAR szSource,
PCHAR szDestination,
PCHAR szPassword)
//--------------------------------------------------------------------
// Parameters passed are:
// szSource, the name of the input, a plaintext file.
// szDestination, the name of the output, an encrypted file to be
// created.
// szPassword, the password.
{
//--------------------------------------------------------------------
// Declare and initialize local variables.
FILE *hSource;
FILE *hDestination;
HCRYPTPROV hCryptProv;
HCRYPTKEY hKey;
HCRYPTHASH hHash;
PBYTE pbBuffer;
DWORD dwBlockLen;
DWORD dwBufferLen;
DWORD dwCount;
//--------------------------------------------------------------------
// Open source file.
if(hSource = fopen(szSource,"rb")) {
printf("The source plaintext file, %s, is open. \n", szSource);
} else {
HandleError("Error opening source plaintext file!");
}
//--------------------------------------------------------------------
// Open destination file.
if(hDestination = fopen(szDestination,"wb")) {
printf("Destination file %s is open. \n", szDestination);
} else {
HandleError("Error opening destination ciphertext file!");
}
//以下获得一个CSP句柄
if(CryptAcquireContext(
&hCryptProv,
NULL, //NULL表示使用默认密钥容器,默认密钥容器名
//为用户登陆名
NULL,
PROV_RSA_FULL,
0)) {
printf("A cryptographic provider has been acquired. \n");
} else {
if(CryptAcquireContext(
&hCryptProv,
NULL,
NULL,
PROV_RSA_FULL,
CRYPT_NEWKEYSET))//创建密钥容器
{
//创建密钥容器成功,并得到CSP句柄
printf("A new key container has been created.\n");
} else {
HandleError("Could not create a new key container.\n");
}
}
//--------------------------------------------------------------------
// 创建一个会话密钥(session key)
// 会话密钥也叫对称密钥,用于对称加密算法。
// (注: 一个Session是指从调用函数CryptAcquireContext到调用函数
// CryptReleaseContext 期间的阶段。会话密钥只能存在于一个会话过程)
//--------------------------------------------------------------------
// Create a hash object.
if(CryptCreateHash(
hCryptProv,
CALG_MD5,
0,
0,
&hHash)) {
printf("A hash object has been created. \n");
} else {
HandleError("Error during CryptCreateHash!\n");
}
//--------------------------------------------------------------------
// 用输入的密码产生一个散列
if(CryptHashData(
hHash,
(BYTE *)szPassword,
strlen(szPassword),
0)) {
printf("The password has been added to the hash. \n");
} else {
HandleError("Error during CryptHashData. \n");
}
//--------------------------------------------------------------------
// 通过散列生成会话密钥
if(CryptDeriveKey(
hCryptProv,
ENCRYPT_ALGORITHM,
hHash,
KEYLENGTH,
&hKey)) {
printf("An encryption key is derived from the password hash. \n");
} else {
HandleError("Error during CryptDeriveKey!\n");
}
//--------------------------------------------------------------------
// Destroy the hash object.
CryptDestroyHash(hHash);
hHash = NULL;
//--------------------------------------------------------------------
// The session key is now ready.
//--------------------------------------------------------------------
// 因为加密算法是按ENCRYPT_BLOCK_SIZE 大小的块加密的,所以被加密的
// 数据长度必须是ENCRYPT_BLOCK_SIZE 的整数倍。下面计算一次加密的
// 数据长度。
dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE;
//--------------------------------------------------------------------
// Determine the block size. If a block cipher is used,
// it must have room for an extra block.
if(ENCRYPT_BLOCK_SIZE > 1)
dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE;
else
dwBufferLen = dwBlockLen;
//--------------------------------------------------------------------
// Allocate memory.
if(pbBuffer = (BYTE *)malloc(dwBufferLen)) {
printf("Memory has been allocated for the buffer. \n");
} else {
HandleError("Out of memory. \n");
}
//--------------------------------------------------------------------
// In a do loop, encrypt the source file and write to the source file.
do {
//--------------------------------------------------------------------
// Read up to dwBlockLen bytes from the source file.
dwCount = fread(pbBuffer, 1, dwBlockLen, hSource);
if(ferror(hSource)) {
HandleError("Error reading plaintext!\n");
}
//--------------------------------------------------------------------
// 加密数据
if(!CryptEncrypt(
hKey, //密钥
0, //如果数据同时进行散列和加密,这里传入一个
//散列对象
feof(hSource), //如果是最后一个被加密的块,输入TRUE.如果不是输.
//入FALSE这里通过判断是否到文件尾来决定是否为
//最后一块。
0, //保留
pbBuffer, //输入被加密数据,输出加密后的数据
&dwCount, //输入被加密数据实际长度,输出加密后数据长度
dwBufferLen)) //pbBuffer的大小。
{
HandleError("Error during CryptEncrypt. \n");
}
//--------------------------------------------------------------------
// Write data to the destination file.
fwrite(pbBuffer, 1, dwCount, hDestination);
if(ferror(hDestination)) {
HandleError("Error writing ciphertext.");
}
} while(!feof(hSource));
//--------------------------------------------------------------------
// End the do loop when the last block of the source file has been
// read, encrypted, and written to the destination file.
//--------------------------------------------------------------------
// Close files.
if(hSource)
fclose(hSource);
if(hDestination)
fclose(hDestination);
//--------------------------------------------------------------------
// Free memory.
if(pbBuffer)
free(pbBuffer);
//--------------------------------------------------------------------
// Destroy session key.
if(hKey)
CryptDestroyKey(hKey);
//--------------------------------------------------------------------
// Destroy hash object.
if(hHash)
CryptDestroyHash(hHash);
//--------------------------------------------------------------------
// Release provider handle.
if(hCryptProv)
CryptReleaseContext(hCryptProv, 0);
return(TRUE);
} // End of Encryptfile
//--------------------------------------------------------------------
// This example uses the function HandleError, a simple error
// handling function, to print an error message to the standard error
// (stderr) file and exit the program.
// For most applications, replace this function with one
// that does more extensive error reporting.
void HandleError(char *s) {
fprintf(stderr,"An error occurred in running the program. \n");
fprintf(stderr,"%s\n",s);
fprintf(stderr, "Error number %x.\n", GetLastError());
fprintf(stderr, "Program terminating. \n");
exit(1);
} // End of HandleError
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
private byte[] Keys = { 0xEF, 0xAB, 0x56, 0x78, 0x90, 0x34, 0xCD, 0x12 };//默认密钥向量
/// <summary>
/// DES加密字符串
/// </summary>
/// <param name="encryptString">待加密的字符串</param>
/// <param name="encryptKey">加密密钥,要求为8位</param>
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public 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 string DecryptDES(string decryptString, string decryptKey)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
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;
}
}
/// <summary>
/// use sha1 to encrypt string
/// </summary>
public string SHA1_Encrypt(string Source_String)
{
byte[] StrRes = Encoding.Default.GetBytes(Source_String);
HashAlgorithm iSHA = new SHA1CryptoServiceProvider();
StrRes = iSHA.ComputeHash(StrRes);
StringBuilder EnText = new StringBuilder();
foreach (byte iByte in StrRes)
{
EnText.AppendFormat("{0:x2}", iByte);
}
return EnText.ToString();
}
namespace Microsoft.Samples.Security.PublicKey
{
class App
{
// Main entry point
static void Main(string[] args)
{
// Instantiate 3 People for example. See the Person class below
Person alice = new Person("Alice");
Person bob = new Person("Bob");
Person steve = new Person("Steve");
// Messages that will exchanged. See CipherMessage class below
CipherMessage aliceMessage;
CipherMessage bobMessage;
CipherMessage steveMessage;
// Example of encrypting/decrypting your own message
Console.WriteLine("Encrypting/Decrypting Your Own Message");
Console.WriteLine("-----------------------------------------");
// Alice encrypts a message using her own public key
aliceMessage = alice.EncryptMessage("Alice wrote this message");
// then using her private key can decrypt the message
alice.DecryptMessage(aliceMessage);
// Example of Exchanging Keys and Messages
Console.WriteLine();
Console.WriteLine("Exchanging Keys and Messages");
Console.WriteLine("-----------------------------------------");
// Alice Sends a copy of her public key to Bob and Steve
bob.GetPublicKey(alice);
steve.GetPublicKey(alice);
// Bob and Steve both encrypt messages to send to Alice
bobMessage = bob.EncryptMessage("Hi Alice! - Bob.");
steveMessage = steve.EncryptMessage("How are you? - Steve");
// Alice can decrypt and read both messages
alice.DecryptMessage(bobMessage);
alice.DecryptMessage(steveMessage);
Console.WriteLine();
Console.WriteLine("Private Key required to read the messages");
Console.WriteLine("-----------------------------------------");
// Steve cannot read the message that Bob encrypted
steve.DecryptMessage(bobMessage);
// Not even Bob can use the Message he encrypted for Alice.
// The RSA private key is required to decrypt the RS2 key used
// in the decryption.
bob.DecryptMessage(bobMessage);
} // method Main
} // class App
class CipherMessage
{
public byte[] cipherBytes; // RC2 encrypted message text
public byte[] rc2Key; // RSA encrypted rc2 key
public byte[] rc2IV; // RC2 initialization vector
}
class Person
{
private RSACryptoServiceProvider rsa;
private RC2CryptoServiceProvider rc2;
private string name;
// Maximum key size for the RC2 algorithm
const int keySize = 128;
// Person constructor
public Person(string p_Name)
{
rsa = new RSACryptoServiceProvider();
rc2 = new RC2CryptoServiceProvider();
rc2.KeySize = keySize;
name = p_Name;
}
// Used to send the rsa public key parameters
public RSAParameters SendPublicKey()
{
RSAParameters result = new RSAParameters();
try
{
result = rsa.ExportParameters(false);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
return result;
}
// Used to import the rsa public key parameters
public void GetPublicKey(Person receiver)
{
try
{
rsa.ImportParameters(receiver.SendPublicKey());
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
}
public CipherMessage EncryptMessage(string text)
{
// Convert string to a byte array
CipherMessage message = new CipherMessage();
byte[] plainBytes = Encoding.Unicode.GetBytes(text.ToCharArray());
// A new key and iv are generated for every message
rc2.GenerateKey();
rc2.GenerateIV();
// The rc2 initialization doesnt need to be encrypted, but will
// be used in conjunction with the key to decrypt the message.
message.rc2IV = rc2.IV;
try
{
// Encrypt the RC2 key using RSA encryption
message.rc2Key = rsa.Encrypt(rc2.Key, false);
}
catch (CryptographicException e)
{
// The High Encryption Pack is required to run this sample
// because we are using a 128-bit key. See the readme for
// additional information.
Console.WriteLine("Encryption Failed. Ensure that the" +
" High Encryption Pack is installed.");
Console.WriteLine("Error Message: " + e.Message);
Environment.Exit(0);
}
// Encrypt the Text Message using RC2 (Symmetric algorithm)
ICryptoTransform sse = rc2.CreateEncryptor();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
try
{
cs.Write(plainBytes, 0, plainBytes.Length);
cs.FlushFinalBlock();
message.cipherBytes = ms.ToArray();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
ms.Close();
cs.Close();
}
return message;
} // method EncryptMessage
public void DecryptMessage(CipherMessage message)
{
// Get the RC2 Key and Initialization Vector
rc2.IV = message.rc2IV;
try
{
// Try decrypting the rc2 key
rc2.Key = rsa.Decrypt(message.rc2Key, false);
}
catch (CryptographicException e)
{
Console.WriteLine("Decryption Failed: " + e.Message);
return;
}
ICryptoTransform ssd = rc2.CreateDecryptor();
// Put the encrypted message in a memorystream
MemoryStream ms = new MemoryStream(message.cipherBytes);
// the CryptoStream will read cipher text from the MemoryStream
CryptoStream cs = new CryptoStream(ms, ssd, CryptoStreamMode.Read);
byte[] initialText = new Byte[message.cipherBytes.Length];
try
{
// Decrypt the message and store in byte array
cs.Read(initialText, 0, initialText.Length);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
ms.Close();
cs.Close();
}
// Display the message received
Console.WriteLine(name + " received the following message:");
Console.WriteLine(" " + Encoding.Unicode.GetString(initialText));
} // method DecryptMessage
} // class Person
} // namespace PublicKey