在最近的開發中,遇到了一個問題,發現Python沒有一個生成指定複雜度密碼的模塊(反正我沒有找到),須要本身寫一段生成隨機數的代碼來生成密碼,所以我就用C++本身寫的一個擴展模塊。python
模塊的要求:ios
上面的要求能夠本身定製,好比說加上特殊字符,都是能夠的,只要稍稍修改下代碼便可。git
頭文件app
// // Created by lanyulei on 18-9-27. // #ifndef GENERATEPASSWORD_GENERATEPASSWORD_H #define GENERATEPASSWORD_GENERATEPASSWORD_H #include <iostream> #include <string> #include <time.h> #include <boost/python.hpp> using namespace boost::python; class GeneratePassword{ public: GeneratePassword(int length); std::string getPassword(); private: int m_intLength; }; #endif //GENERATEPASSWORD_GENERATEPASSWORD_H
源文件python2.7
// // 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<length; 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<m_intLength; i++) { int idx = rand()%62; sprintf(buf, "%c", chr[idx]); strResult.append(buf); } } gcounts++; } return strResult; } // 生成Python可調用的動態連接庫 BOOST_PYTHON_MODULE(gpassword){ class_<GeneratePassword> ("gpassword", init<int>()) .def("getPassword", &GeneratePassword::getPassword); }
編譯命令ide
# 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,若有好的意見請不吝賜教,很是感謝。spa