summaryrefslogtreecommitdiff
path: root/pysnmp/proto/secmod/rfc3414/localkey.py
blob: 144342fa1a10491814be6b9e7f59a33ac83e7480 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pysnmp/license.html
#
from hashlib import md5
from hashlib import sha1

from pyasn1.type import univ


def hashPassphrase(passphrase, hashFunc):
    passphrase = univ.OctetString(passphrase).asOctets()
    hasher = hashFunc()
    ringBuffer = passphrase * (64 // len(passphrase) + 1)
    ringBufferLen = len(ringBuffer)
    count = 0
    mark = 0

    while count < 16384:
        e = mark + 64
        if e < ringBufferLen:
            hasher.update(ringBuffer[mark:e])
            mark = e

        else:
            hasher.update(
                ringBuffer[mark:ringBufferLen] + ringBuffer[0:e - ringBufferLen]
            )
            mark = e - ringBufferLen

        count += 1

    return hasher.digest()


def passwordToKey(passphrase, snmpEngineId, hashFunc):
    return localizeKey(hashPassphrase(passphrase, hashFunc), snmpEngineId, hashFunc)


def localizeKey(passKey, snmpEngineId, hashFunc):
    passKey = univ.OctetString(passKey).asOctets()
    # noinspection PyDeprecation,PyCallingNonCallable
    return hashFunc(passKey + snmpEngineId.asOctets() + passKey).digest()


# RFC3414: A.2.1
def hashPassphraseMD5(passphrase):
    return hashPassphrase(passphrase, md5)


# RFC3414: A.2.2
def hashPassphraseSHA(passphrase):
    return hashPassphrase(passphrase, sha1)


def passwordToKeyMD5(passphrase, snmpEngineId):
    return localizeKey(hashPassphraseMD5(passphrase), snmpEngineId, md5)


def passwordToKeySHA(passphrase, snmpEngineId):
    return localizeKey(hashPassphraseMD5(passphrase), snmpEngineId, sha1)


def localizeKeyMD5(passKey, snmpEngineId):
    return localizeKey(passKey, snmpEngineId, md5)


def localizeKeySHA(passKey, snmpEngineId):
    return localizeKey(passKey, snmpEngineId, sha1)