python生成密码库_C++ 编写Python扩展(密码生成器)

简介

在最近的开发中,遇到了一个问题,发现Python没有一个生成指定复杂度密码的模块(反正我没有找到),需要自己写一段生成随机数的代码来生成密码,因此我就用C++自己写的一个扩展模块。

模块的要求:

必须同时包含大写小写和数字

可以传递参数设置密码长度

上面的要求可以自己定制,比如说加上特殊字符,都是可以的,只要稍稍修改下代码即可。

源码

头文件

//

// Created by lanyulei on 18-9-27.

//

#ifndef GENERATEPASSWORD_GENERATEPASSWORD_H

#define GENERATEPASSWORD_GENERATEPASSWORD_H

#include

#include

#include

#include

using namespace boost::python;

class GeneratePassword{

public:

GeneratePassword(int length);

std::string getPassword();

private:

int m_intLength;

};

#endif //GENERATEPASSWORD_GENERATEPASSWORD_H

源文件

//

// Created by lanyulei on 18-9-27.

//

#include "GeneratePassword.h"

using namespace std;

// 判断密码复杂度是否符合要求

bool judgment(const string& passowrdValue, int length) {

int Pcount = 0;

int pcount = 0;

int numberCount = 0;

for (int i=0; i

if (isupper(passowrdValue[i])) {

Pcount++;

} else if (islower(passowrdValue[i])) {

pcount++;

} else if (isdigit(passowrdValue[i])) {

numberCount++;

}

}

if (Pcount && pcount && numberCount) {

return true;

} else {

return false;

}

}

// 构造函数,设置密码生成位数

GeneratePassword::GeneratePassword(int length):m_intLength(length){}

// 生成密码,并且返回

string GeneratePassword::getPassword() {

char chr[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',

'A', 'B', 'C', 'D', 'E', 'F', 'G',

'H', 'I', 'J', 'K', 'L', 'M', 'N',

'O', 'P', 'Q', 'R', 'S', 'T', 'U',

'V', 'W', 'X', 'Y', 'Z',

'a', 'b', 'c', 'd', 'e', 'f', 'g',

'h', 'i', 'j', 'k', 'l', 'm', 'n',

'o', 'p', 'q', 'r', 's', 't', 'u',

'v', 'w', 'x', 'y', 'z'

};

string strResult;

int gcounts = 0;

while (gcounts < 10) {

if (judgment(strResult, m_intLength)) {

break;

} else {

strResult.clear();

char buf[10] = {0};

for (int i=0; i

int idx = rand()%62;

sprintf(buf, "%c", chr[idx]);

strResult.append(buf);

}

}

gcounts++;

}

return strResult;

}

// 生成Python可调用的动态链接库

BOOST_PYTHON_MODULE(gpassword){

class_

("gpassword", init())

.def("getPassword", &GeneratePassword::getPassword);

}

编译命令

# python3

g++ -shared -o helloworld.so -fPIC -I/usr/include/python3.6m/ helloworld.cpp -lpython3.6m -lboost_python3

# python2

g++ -shared -o helloworld.so -fPIC -I/usr/include/python2.7/ helloworld.cpp -lpython -lboost_python

效果展示

In [2]: import gpassword

In [3]: gp = gpassword.gpassword(18) // 实例化,并且设置生成多少位的密码

In [4]: gp.getPassword() // 生成密码

Out[4]: 'fa37JncCHryDsbzayy'

写的有点low,如有好的意见请不吝赐教,非常感谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值