Sloppy's Blog

IOS使用cryptopp(Cocos2d-x项目)

相信很多的项目中经常要用到各种不同的加密解密的问题,加密主要分为:

  • 对称加解密,就是需要密钥才能加密解密.加解密双方都需要密钥
  • 非对称加密,一般是使用公私钥的方式,公钥加密,私钥解密
  • 不可逆加密,广泛用于常用的MD5,用户密码加密,字符串比较小,当然现在计算机性能好.可以加密很大的字符串.性能也没有问题

准备工作

我们使用的c++ 库,cryptopp,包含了各种加密方式,我们先下载:https://www.cryptopp.com/#download,这里我用的是5.6.2版本。解压Zip,我们先在Windows是打开:cryptest.sln。编译结束后,进入cryptopp562\Win32\Output\Debug目录,打开命令行。运行如下命令:

cryptest.exe r
输入:私钥文件名,公钥文件名,Seed字符串,输入要加密的字符串,这里我输入的是:HelloWorld,好了。我们把当前目录下的。私钥文件(PrivateKey),以及加密后的密文Copy到r.txt文本文件中(新建一个r.txt文件)。 ### IOS平台 打开我们事先建的Cocos2d-x项目,新建一个目录cryptopp,并添加进Xcode项目,把cryptopp562目录下的所有的源文件(h文件,CPP文件),复制到文件目录,这里我们删除一些不需要的文件,我这里删除的是(validat1.cpp,validat2.cpp,validat3.cpp,bench.cpp,bench2.cpp,test.cpp),把上面产生的私钥文件跟文本文件,放到项目的Resources/res目录下 修改HelloWorldScene.cpp代码。 添加如下头文件引用:
include "cryptopp/rsa.h"
include "cryptopp/files.h"
include "cryptopp/hex.h"
include "cryptopp/filters.h"
include "cryptopp/modes.h"
include "cryptopp/aes.h"

// 引用命名空间
using namespace CryptoPP;
using namespace std;

定义几个对象
typedef CryptoPP::RSAES >::Decryptor RSAES_OAEP_SHA_Decryptor;
static OFB_Mode::Encryption s_globalRNG;

定义解密方法:
std::string RSADecryptString(const char *privFilename, const char *ciphertext)
{
    CryptoPP::FileSource privFile(privFilename, true, new HexDecoder);
    RSAES_OAEP_SHA_Decryptor priv(privFile);
    string result;
    StringSource(ciphertext, true, new HexDecoder(new PK_DecryptorFilter(s_globalRNG, priv, new StringSink(result))));
    return result;
}

在HelloWorld::init方法最后面添加如下代码:

std::string seed = IntToString(time(NULL));
seed.resize(16);
s_globalRNG.SetKeyWithIV((byte *)seed.data(), 16, (byte *)seed.data());

std::string cipherTxt=FileUtils::getInstance()->getStringFromFile("res/r.txt");
std::string privateKeyFile = FileUtils::getInstance()->fullPathForFilename("res/PrivateKey");
std::string txt = RSADecryptString(privateKeyFile.c_str(),cipherTxt.c_str());
CCLOG("originaleTxt:%s",txt.c_str());

是不是在控制台输出了:HelloWorld字符串?这里面我们演示的是加密的第二种方法,通常这种方式,私钥是解密者所有,公钥是加密者所有。

计算字符串的MD5值:

byte digest[CryptoPP::MD5::DIGESTSIZE];
std::string message = "HelloWorld";
CryptoPP::MD5 hash;
hash.CalculateDigest(digest, (const byte*)message.c_str(), message.size());
CryptoPP::HexEncoder encoder;
std::string output;
encoder.Attach(new CryptoPP::StringSink(output));
encoder.Put(digest,sizeof(digest));
encoder.MessageEnd();