22

Windows XP で Python を使用して DPAPI (Data Protection Application Programming Interface) を使用する方法はありますか?

それができるモジュールがあれば、既存のモジュールを使用したいと思います。残念ながら、Google や Stack Overflow で方法を見つけることができませんでした。

編集:「dF」で示されているサンプル コードを取得し、ユーザー モードで DPAPI を使用して暗号化および復号化するために高レベルで簡単に使用できるスタンドアロン ライブラリに微調整しました。暗号化された文字列を返す dpapi.cryptData(text_to_encrypt) を呼び出すか、プレーン テキストを返す逆の decryptData(encrypted_data_string) を呼び出すだけです。ライブラリは次のとおりです。

# DPAPI access library
# This file uses code originally created by Crusher Joe:
# http://article.gmane.org/gmane.comp.python.ctypes/420
#

from ctypes import *
from ctypes.wintypes import DWORD

LocalFree = windll.kernel32.LocalFree
memcpy = cdll.msvcrt.memcpy
CryptProtectData = windll.crypt32.CryptProtectData
CryptUnprotectData = windll.crypt32.CryptUnprotectData
CRYPTPROTECT_UI_FORBIDDEN = 0x01
extraEntropy = "cl;ad13 \0al;323kjd #(adl;k$#ajsd"

class DATA_BLOB(Structure):
    _fields_ = [("cbData", DWORD), ("pbData", POINTER(c_char))]

def getData(blobOut):
    cbData = int(blobOut.cbData)
    pbData = blobOut.pbData
    buffer = c_buffer(cbData)
    memcpy(buffer, pbData, cbData)
    LocalFree(pbData);
    return buffer.raw

def Win32CryptProtectData(plainText, entropy):
    bufferIn = c_buffer(plainText, len(plainText))
    blobIn = DATA_BLOB(len(plainText), bufferIn)
    bufferEntropy = c_buffer(entropy, len(entropy))
    blobEntropy = DATA_BLOB(len(entropy), bufferEntropy)
    blobOut = DATA_BLOB()

    if CryptProtectData(byref(blobIn), u"python_data", byref(blobEntropy),
                       None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)):
        return getData(blobOut)
    else:
        return ""

def Win32CryptUnprotectData(cipherText, entropy):
    bufferIn = c_buffer(cipherText, len(cipherText))
    blobIn = DATA_BLOB(len(cipherText), bufferIn)
    bufferEntropy = c_buffer(entropy, len(entropy))
    blobEntropy = DATA_BLOB(len(entropy), bufferEntropy)
    blobOut = DATA_BLOB()
    if CryptUnprotectData(byref(blobIn), None, byref(blobEntropy), None, None,
                              CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)):
        return getData(blobOut)
    else:
        return ""

def cryptData(text):
    return Win32CryptProtectData(text, extraEntropy)

def decryptData(cipher_text):
    return Win32CryptUnprotectData(cipher_text, extraEntropy)
4

3 に答える 3

10

私はctypesを使用CryptProtectDataしており、コードはCryptUnprotectData

http://article.gmane.org/gmane.comp.python.ctypes/420

そしてそれはうまく機能しています。

于 2009-01-21T01:37:54.677 に答える
6

また、pywin32は、win32cryptモジュールにCryptProtectDataとCryptUnprotectDataを実装します。

于 2009-10-13T19:20:07.503 に答える
2

最も簡単な方法は、IronPythonを使用することです

于 2009-01-21T01:34:50.270 に答える