📄 cryptlibconverter.py
字号:
return 1;}static int getPointerReadString(PyObject* objPtr, char** charPtrPtr){ int length = 0; char* newPtr = NULL; if (objPtr == Py_None) { *charPtrPtr = NULL; return 1; } /*See if it's a string or a buffer object*/ if (PyObject_AsCharBuffer(objPtr, charPtrPtr, &length) == -1) { /*See if it's an array*/ PyErr_Clear(); if (PyObject_AsWriteBuffer(objPtr, charPtrPtr, &length) == -1) return 0; } /*This code isn't necessary for a string, but it is for arrays and buffers, so we do it always anyway, since the PyObject_AsCharBuffer apparently doesn't guarantee us null-terminated data, and this way releasePointerString() doesn't have to differentiate */ newPtr = malloc(length+1); if (newPtr == NULL) { PyErr_NoMemory(); return 0; } memcpy(newPtr, *charPtrPtr, length); newPtr[length] = 0; *charPtrPtr = newPtr; return 1;}static void releasePointer(PyObject* objPtr, unsigned char* bytesPtr){}static void releasePointerString(PyObject* objPtr, char* charPtr){ free(charPtr);}static PyObject* processStatus(int status){ PyObject* o = NULL; /* If an error has already occurred, ignore the status and just fall through */ if (PyErr_Occurred()) return(NULL); if (status >= CRYPT_OK) return(Py_BuildValue(""));""" pyBeforeFuncs = """\ PyErr_SetObject(CryptException, o); Py_DECREF(o); return(NULL);}static int processStatusBool(int status){ PyObject* o = processStatus(status); if (o == NULL) return(0); else { Py_DECREF(o); return(1); }}static PyObject* processStatusReturnInt(int status, int returnValue){ PyObject* o = processStatus(status); if (o == NULL) return(0); else { Py_DECREF(o); o = Py_BuildValue("i", returnValue); return(o); }}static PyObject* processStatusReturnCryptHandle(int status, int returnValue){ PyObject* o2; PyObject* o = processStatus(status); if (o == NULL) return(0); else { Py_DECREF(o); o2 = Py_BuildValue("(i)", returnValue); o = PyObject_CallObject(cryptHandleClass, o2); Py_DECREF(o2); return(o); }}static PyObject* processStatusReturnCryptQueryInfo(int status, CRYPT_QUERY_INFO returnValue){ PyObject* o2; PyObject* o = processStatus(status); if (o == NULL) return(0); else { Py_DECREF(o); o2 = Py_BuildValue("(siiii)", returnValue.algoName, returnValue.blockSize, returnValue.minKeySize, returnValue.keySize, returnValue.maxKeySize); o = PyObject_CallObject(cryptQueryInfoClass, o2); Py_DECREF(o2); return(o); }}static PyObject* processStatusReturnCryptObjectInfo(int status, CRYPT_OBJECT_INFO returnValue){ PyObject* o2; PyObject* o = processStatus(status); if (o == NULL) return(0); else { Py_DECREF(o); o2 = Py_BuildValue("(iiiis#)", returnValue.objectType, returnValue.cryptAlgo, returnValue.cryptMode, returnValue.hashAlgo, returnValue.salt, returnValue.saltSize); o = PyObject_CallObject(cryptObjectInfoClass, o2); Py_DECREF(o2); return(o); }}""" pyBeforeModuleFunctions = """static PyMethodDef module_functions[] ={""" pyBeforeInts = r""" {0, 0}};DL_EXPORT(void) initcryptlib_py(void){ PyObject* module; PyObject* moduleDict; PyObject* v = NULL; PyObject *globalsDict; module = Py_InitModule("cryptlib_py", module_functions); moduleDict = PyModule_GetDict(module); CryptException = PyErr_NewException("cryptlib_py.CryptException", NULL, NULL); PyDict_SetItemString(moduleDict, "CryptException", CryptException); globalsDict = PyEval_GetGlobals(); PyRun_String("from array import *\n\import types\n\class CryptHandle:\n\ def __init__(self, value):\n\ self.__dict__['value'] = value\n\ def __int__(self):\n\ return self.value\n\ def __str__(self):\n\ return str(self.value)\n\ def __repr__(self):\n\ return str(self.value)\n\ def __getattr__(self, name):\n\ name = name.upper()\n\ if not name.startswith('CRYPT_'):\n\ name = 'CRYPT_' + name\n\ nameVal = globals()[name]\n\ try:\n\ return cryptGetAttribute(self, nameVal)\n\ except CryptException, ex:\n\ length = cryptGetAttributeString(self, nameVal, None)\n\ buf = array('c', '0' * length)\n\ length = cryptGetAttributeString(self, nameVal, buf)\n\ return ''.join(buf[:length])\n\ def __setattr__(self, name, value):\n\ name = name.upper()\n\ if not name.startswith('CRYPT_'):\n\ name = 'CRYPT_' + name\n\ nameVal = globals()[name]\n\ if isinstance(value, types.IntType) or isinstance(value, CryptHandle):\n\ cryptSetAttribute(self, nameVal, value)\n\ else:\n\ cryptSetAttributeString(self, nameVal, value)\n", Py_file_input, globalsDict, moduleDict); PyRun_String("class CRYPT_QUERY_INFO:\n\ def __init__(self, algoName, blockSize, minKeySize, keySize, maxKeySize):\n\ self.algoName = algoName\n\ self.blockSize = blockSize\n\ self.minKeySize = minKeySize\n\ self.keySize = keySize\n\ self.maxKeySize = maxKeySize\n", Py_file_input, globalsDict, moduleDict); PyRun_String("class CRYPT_OBJECT_INFO:\n\ def __init__(self, objectType, cryptAlgo, cryptMode, hashAlgo, salt):\n\ self.objectType = objectType\n\ self.cryptAlgo = cryptAlgo\n\ self.cryptMode = cryptMode\n\ self.hashAlgo = hashAlgo\n\ self.salt = salt\n", Py_file_input, globalsDict, moduleDict); cryptHandleClass = PyMapping_GetItemString(moduleDict, "CryptHandle"); cryptQueryInfoClass = PyMapping_GetItemString(moduleDict, "CRYPT_QUERY_INFO"); cryptObjectInfoClass = PyMapping_GetItemString(moduleDict, "CRYPT_OBJECT_INFO"); Py_DECREF(globalsDict);""" pyAfterInts = "}" paramCharPtrTemplate = "%(name)s, # string\n" paramIntTemplate = "%(name)s, # integer\n" paramIntTypeTemplate = "%(name)s, # %(type)s\n" paramEnumTypeTemplate = "%(name)s, # %(type)s\n" commentPrefix = "# " #pad to 2-characters for formatting consistency classPrefix = "class crypt:\n" classPostfix= "" outFile = os.path.join(outDir, "cryptlib.py") sFuncs = "\n" sInts = "\n" sModFuncs = "" setupPy = r"""#!/usr/bin/env pythonfrom distutils.core import setup, Extensionimport sysif sys.platform == "win32": ext = Extension("cryptlib_py", sources=["python.c"], library_dirs=['../binaries'], libraries=['cl32'])else: ext = Extension("cryptlib_py", sources=["python.c"], library_dirs=['..'], libraries=['cl'])setup(name="cryptlib_py", ext_modules=[ext])"""elif language == "net": typedefEnumTemplate = "// %(typedefName)s" typedefEnumElementTemplate = "public const int %(name)-NPADs = %(value)-VPADs;" typedefEnumElementTemplateComment = typedefEnumElementTemplate + " // %(comment)s" simpleEnumElementTemplate = "public const int %(name)-NPADs = %(value)-VPADs;" simpleEnumElementTemplateComment = simpleEnumElementTemplate + " // %(comment)s" defineNPad = "40" defineVPad = "4" defineTemplate = simpleEnumElementTemplate defineTemplateComment = simpleEnumElementTemplateComment exceptionPrefix = """[StructLayout(LayoutKind.Sequential, Pack=0, CharSet=CharSet.Ansi)]public class CRYPT_QUERY_INFO{ [MarshalAs(UnmanagedType.ByValTStr, SizeConst=64)]public String algoName; public int blockSize; public int minKeySize; public int keySize; public int maxKeySize; public CRYPT_QUERY_INFO(){} public CRYPT_QUERY_INFO(String newAlgoName, int newBlockSize, int newMinKeySize, int newKeySize, int newMaxKeySize) { algoName = newAlgoName; blockSize = newBlockSize; minKeySize = newMinKeySize; keySize = newKeySize; maxKeySize = newMaxKeySize; }}[StructLayout(LayoutKind.Sequential, Pack=0, CharSet=CharSet.Ansi)]public class CRYPT_OBJECT_INFO{ public int objectType; public int cryptAlgo; public int cryptMode; public int hashAlgo; [MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]public byte[] salt; public int saltSize; public CRYPT_OBJECT_INFO() { salt = new byte[64]; saltSize = 64; } public CRYPT_OBJECT_INFO(int newObjectType, int newCryptAlgo, int newCryptMode, int newHashAlgo, byte[] newSalt) { objectType = newObjectType; cryptAlgo = newCryptAlgo; cryptMode = newCryptMode; hashAlgo = newHashAlgo; }}public class CryptException : ApplicationException{ private int m_status; private String m_message; public int Status { get {return m_status;} } public override String Message { get {return m_message;} } public CryptException(int status) { m_status = status; String prefix = Convert.ToString(status) + ": ";""" exceptionPostfix = """\ m_message = prefix + "Unknown Exception ?!?!"; }}""" exceptionTemplate = """\ if (m_status == crypt.%(name)s) { m_message = prefix + "%(comment)s"; return; }""" addFunctionWrappers = 1 wholeFunctionDeclaration = None functionDeclaration = "public static " returnIntDeclaration = "int " returnVoidDeclaration = "void " paramsPrefix = "(" paramsPostfix = ");" paramWhiteSpace = "\t\t\t\t\t\t" paramVoidPtrTemplate = "byte[] %(name)s,\n" addFunctionAlternate = 0 paramCharPtrTemplate = "String %(name)s,\n" paramIntTemplate = "int %(name)s,\n" paramIntTypeTemplate = "int %(name)s, // %(type)s\n" wrapperLengthTemplate = "%(1)s == null ? 0 : %(1)s.Length, " wrapperStringLengthTemplate = "%(1)s == null ? 0 : new UTF8Encoding().GetByteCount(%(1)s), " wrapperStringReplace = ("byte[]", "String") wrapperStringTemplate = "%(1)s == null ? null : new UTF8Encoding().GetBytes(%(1)s)" #ENUM IDIOM #paramEnumTypeTemplate = "%(type)s %(name)s,\n" #ENUMs as ints paramEnumTypeTemplate = "int %(name)s, // %(type)s\n" commentPrefix = "//" classPrefix = """using System;using System.Runtime.InteropServices;using System.Text;namespace cryptlib{public class crypt{ """ classPostfix = """ /* Helper Functions */
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -