win_crypto.cpp

来自「windowxp 下各种系统提供的加密方法:rsa,des,sha,md5」· C++ 代码 · 共 121 行

CPP
121
字号
// win_crypto.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include "KrCrypto.h"

#include <atlbase.h>
#include <atlcrypt.h>
#include <atlenc.h>

#include <string>
using namespace std;

#include "Crypt.h"



void test();
void test_2();

int _tmain(int argc, _TCHAR* argv[])
{
	test_2();
	return 0;
}

void readstr(LPCTSTR lpszFileName, std::string& str)
{
	FILE* fp = fopen(lpszFileName, "rb");

	if ( fp == NULL )
		return;

	fseek(fp, 0, SEEK_END);
	int iSize = ftell(fp);

	str.resize(iSize, 0);

	fseek(fp, 0, SEEK_SET);
	fread(&str[0], 1, iSize, fp);

	fclose(fp);
}

void writestr(LPCTSTR lpszFileName, std::string& str)
{
	if ( str.empty() )
		return;

	FILE* fp = fopen(lpszFileName, "wb");

	if ( fp == NULL )
		return;

	fwrite(&str[0], 1, str.size(), fp);

	fclose(fp);
}

void test_2()
{
	std::string strText("这是加密之前的文本,文本长度比较短,可以当作密钥来处理");

	std::string strPubKey, strPrvKey, strRandKey;

	CKrCrypto krCrypt;
	if ( !krCrypt.GenRsaKeyPair(strPubKey, strPrvKey) )
		return;

	if ( !krCrypt.RandomEnCrypt(strText, strPubKey, strRandKey) )
		return;

	if ( !krCrypt.RandomDeCrypt(strText, strPrvKey, strRandKey) )
		return;

	cout << strText << endl;

	std::string strMd5;
	krCrypt.Md5Hash(strText, strMd5);
	krCrypt.Hex16Encode(strMd5);

	cout << "md5:" << strMd5 << endl;

	std::string strSha1;
	krCrypt.Sha1Hash(strText, strSha1);
	krCrypt.Hex16Encode(strSha1);

	cout << "sha1:" << strSha1 << endl;

	krCrypt.SimpleEnCrypt(strText, "this is my key blobs, please use it");
	krCrypt.Hex16Encode(strText);
	cout << "simple encrypt:" << strText << endl;

	krCrypt.Hex16Decode(strText);
	krCrypt.SimpleEnCrypt(strText, "this is my key blobs, please use it");
	cout << "simple decrypt:" << strText << endl << endl;

	if ( !krCrypt.RsaEnCrypt(strText, strPrvKey) )
		return;
	if ( !krCrypt.RsaDecrypt(strText, strPubKey) )
		return;

	cout << "Rsa EnDe: " << strText << endl;
}

void test()
{
	CKrCrypto krCrypt;

	std::string strPrvKey, strSessKey, strEnText;

	readstr("PrivateKey.txt", strPrvKey);
	readstr("SessionKey.bin", strSessKey);
	readstr("CipherText.bin", strEnText);

	krCrypt.Base64Decode(strPrvKey);
	krCrypt.RandomDeCrypt(strEnText, strPrvKey, strSessKey);

	cout << strEnText << endl;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?