PyOTP 1.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyotp-1.3.0/PKG-INFO ADDED
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 1.0
2
+ Name: pyotp
3
+ Version: 1.3.0
4
+ Summary: https://github.com/nathforge/pyotp
5
+ Home-page: https://github.com/nathforge/pyotp
6
+ Author: Mark Percival (ported by Nathan Reynolds to Python)
7
+ Author-email: nath@nreynolds.co.uk
8
+ License: UNKNOWN
9
+ Description: UNKNOWN
10
+ Platform: UNKNOWN
@@ -0,0 +1,78 @@
1
+ # PYOTP - The Python One Time Password Library
2
+
3
+ A Python library for generating one time passwords according to[ RFC 4226 ](http://tools.ietf.org/html/rfc4226) and the [ HOTP RFC ](http://tools.ietf.org/html/draft-mraihi-totp-timebased-00), ported from Mark Percival's [ ROTP ](https://github.com/mdp/rotp).
4
+
5
+ This is compatible with Google Authenticator apps available for Android and iPhone, and now in use on GMail
6
+
7
+ ## Quick overview of using One Time Passwords on your phone
8
+
9
+ * OTP's involve a shared secret, stored both on the phone and the server
10
+ * OTP's can be generated on a phone without internet connectivity(AT&T mode)
11
+ * OTP's should always be used as a second factor of authentication(if your phone is lost, you account is still secured with a password)
12
+ * Google Authenticator allows you to store multiple OTP secrets and provision those using a QR Code(no more typing in the secret)
13
+
14
+ ## Installation
15
+
16
+ pip install pyotp
17
+
18
+ ## Use
19
+
20
+ ### Time based OTP's
21
+
22
+ totp = pyotp.TOTP('base32secret3232')
23
+ totp.now() # => 492039
24
+
25
+ # OTP verified for current time
26
+ totp.verify(492039) # => True
27
+ time.sleep(30)
28
+ totp.verify(492039) # => False
29
+
30
+ ### Counter based OTP's
31
+
32
+ hotp = pyotp.HOTP('base32secret3232')
33
+ hotp.at(0) # => 260182
34
+ hotp.at(1) # => 55283
35
+ hotp.at(1401) # => 316439
36
+
37
+ # OTP verified with a counter
38
+ hotp.verify(316439, 1401) # => True
39
+ hotp.verify(316439, 1402) # => False
40
+
41
+ ### Generating a Base32 Secret key
42
+
43
+ pyotp.random_base32() # returns a 16 character base32 secret. Compatible with Google Authenticator
44
+
45
+ ### Google Authenticator Compatible
46
+
47
+ The library works with the Google Authenticator iPhone and Android app, and also
48
+ includes the ability to generate provisioning URI's for use with the QR Code scanner
49
+ built into the app.
50
+
51
+ totp.provisioning_uri("alice@google.com") # => 'otpauth://totp/alice@google.com?secret=JBSWY3DPEHPK3PXP'
52
+ hotp.provisioning_uri("alice@google.com", 0) # => 'otpauth://hotp/alice@google.com?secret=JBSWY3DPEHPK3PXP&counter=0'
53
+
54
+ This can then be rendered as a QR Code which can then be scanned and added to the users
55
+ list of OTP credentials.
56
+
57
+ #### Working example
58
+
59
+ Scan the following barcode with your phone, using Google Authenticator
60
+
61
+ ![QR Code for OTP](http://chart.apis.google.com/chart?cht=qr&chs=250x250&chl=otpauth%3A%2F%2Ftotp%2Falice%40google.com%3Fsecret%3DJBSWY3DPEHPK3PXP)
62
+
63
+ Now run the following and compare the output
64
+
65
+ import pyotp
66
+ totp = pyotp.TOTP("JBSWY3DPEHPK3PXP")
67
+ print "Current OTP: %s" % totp.now()
68
+
69
+ ### Changelog
70
+
71
+ ####1.3.0
72
+
73
+ - Ported to Python
74
+
75
+ ### See also:
76
+
77
+ Original Ruby version of ROTP by [Mark Percival](https://github.com/mdp) - [ROTP](https://github.com/mdp/rotp)
78
+ PHP port of ROTP by [Le Lag](https://github.com/lelag) - [OTPHP](https://github.com/lelag/otphp)
pyotp-1.3.0/setup.py ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env python
2
+
3
+ from distutils.core import setup
4
+
5
+ setup(
6
+ version='1.3.0',
7
+ url='https://github.com/nathforge/pyotp',
8
+ name='pyotp',
9
+ description='https://github.com/nathforge/pyotp',
10
+ author='Mark Percival (ported by Nathan Reynolds to Python)',
11
+ author_email='nath@nreynolds.co.uk',
12
+ packages=['pyotp'],
13
+ package_dir={'': 'src'},
14
+ )
@@ -0,0 +1,16 @@
1
+ from pyotp.otp import OTP
2
+ from pyotp.hotp import HOTP
3
+ from pyotp.totp import TOTP
4
+ import base64
5
+ import random
6
+
7
+
8
+ VERSION = '1.3.0'
9
+
10
+
11
+ def random_base32(length=16, random=random.SystemRandom(),
12
+ chars=base64._b32alphabet.values()):
13
+ return ''.join(
14
+ random.choice(chars)
15
+ for i in xrange(length)
16
+ )
@@ -0,0 +1,35 @@
1
+ from pyotp.otp import OTP
2
+ import urllib
3
+
4
+
5
+ class HOTP(OTP):
6
+ def at(self, count):
7
+ """
8
+ Generates the OTP for the given count
9
+ @param [Integer] count counter
10
+ @returns [Integer] OTP
11
+ """
12
+ return self.generate_otp(count)
13
+
14
+ def verify(self, otp, counter):
15
+ """
16
+ Verifies the OTP passed in against the current time OTP
17
+ @param [String/Integer] otp the OTP to check against
18
+ @param [Integer] counter the counter of the OTP
19
+ """
20
+ return otp == self.at(counter)
21
+
22
+ def provisioning_uri(self, name, initial_count=0):
23
+ """
24
+ Returns the provisioning URI for the OTP
25
+ This can then be encoded in a QR Code and used
26
+ to provision the Google Authenticator app
27
+ @param [String] name of the account
28
+ @param [Integer] initial_count starting counter value, defaults to 0
29
+ @return [String] provisioning uri
30
+ """
31
+ return 'otpauth://hotp/%(name)s?secret=%(secret)s&counter=%(initial_count)s' % {
32
+ 'name': urllib.quote(name, safe='@'),
33
+ 'secret': self.secret,
34
+ 'initial_count': initial_count,
35
+ }
@@ -0,0 +1,54 @@
1
+ import base64
2
+ import hashlib
3
+ import hmac
4
+
5
+
6
+ class OTP(object):
7
+ def __init__(self, s, digits=6, digest=hashlib.sha1):
8
+ """
9
+ @param [String] secret in the form of base32
10
+ @option options digits [Integer] (6)
11
+ Number of integers in the OTP
12
+ Google Authenticate only supports 6 currently
13
+ @option options digest [Callable] (hashlib.sha1)
14
+ Digest used in the HMAC
15
+ Google Authenticate only supports 'sha1' currently
16
+ @returns [OTP] OTP instantiation
17
+ """
18
+ self.digits = digits
19
+ self.digest = digest
20
+ self.secret = s
21
+
22
+ def generate_otp(self, input):
23
+ """
24
+ @param [Integer] input the number used seed the HMAC
25
+ Usually either the counter, or the computed integer
26
+ based on the Unix timestamp
27
+ """
28
+ hmac_hash = hmac.new(
29
+ self.byte_secret(),
30
+ self.int_to_bytestring(input),
31
+ self.digest,
32
+ ).digest()
33
+
34
+ offset = ord(hmac_hash[19]) & 0xf
35
+ code = ((ord(hmac_hash[offset]) & 0x7f) << 24 |
36
+ (ord(hmac_hash[offset + 1]) & 0xff) << 16 |
37
+ (ord(hmac_hash[offset + 2]) & 0xff) << 8 |
38
+ (ord(hmac_hash[offset + 3]) & 0xff))
39
+ return code % 10 ** self.digits
40
+
41
+ def byte_secret(self):
42
+ return base64.b32decode(self.secret, casefold=True)
43
+
44
+ def int_to_bytestring(self, int, padding=8):
45
+ """
46
+ Turns an integer to the OATH specified
47
+ bytestring, which is fed to the HMAC
48
+ along with the secret
49
+ """
50
+ result = []
51
+ while int != 0:
52
+ result.append(chr(int & 0xFF))
53
+ int = int >> 8
54
+ return ''.join(reversed(result)).rjust(padding, '\0')
@@ -0,0 +1,57 @@
1
+ from pyotp.otp import OTP
2
+ import datetime
3
+ import time
4
+ import urllib
5
+
6
+
7
+ class TOTP(OTP):
8
+ def __init__(self, *args, **kwargs):
9
+ """
10
+ @option options [Integer] interval (30) the time interval in seconds for OTP
11
+ This defaults to 30 which is standard.
12
+ """
13
+ self.interval = kwargs.pop('interval', 30)
14
+ super(TOTP, self).__init__(*args, **kwargs)
15
+
16
+ def at(self, for_time):
17
+ """
18
+ Accepts either a Unix timestamp integer or a Time object.
19
+ Time objects will be adjusted to UTC automatically
20
+ @param [Time/Integer] time the time to generate an OTP for
21
+ """
22
+ if not isinstance(for_time, datetime.datetime):
23
+ for_time = datetime.datetime.fromtimestamp(int(for_time))
24
+ return self.generate_otp(self.timecode(for_time))
25
+
26
+ def now(self):
27
+ """
28
+ Generate the current time OTP
29
+ @return [Integer] the OTP as an integer
30
+ """
31
+ return self.generate_otp(self.timecode(datetime.datetime.now()))
32
+
33
+ def verify(self, otp, for_time=None):
34
+ """
35
+ Verifies the OTP passed in against the current time OTP
36
+ @param [String/Integer] otp the OTP to check against
37
+ """
38
+ if for_time is None:
39
+ for_time = datetime.datetime.now()
40
+ return otp == self.at(for_time)
41
+
42
+ def provisioning_uri(self, name):
43
+ """
44
+ Returns the provisioning URI for the OTP
45
+ This can then be encoded in a QR Code and used
46
+ to provision the Google Authenticator app
47
+ @param [String] name of the account
48
+ @return [String] provisioning uri
49
+ """
50
+ return 'otpauth://totp/%(name)s?secret=%(secret)s' % {
51
+ 'name': urllib.quote(name, safe='@'),
52
+ 'secret': self.secret,
53
+ }
54
+
55
+ def timecode(self, for_time):
56
+ i = time.mktime(for_time.timetuple())
57
+ return int(i / self.interval)
pyotp-1.3.0/test.py ADDED
@@ -0,0 +1,87 @@
1
+ from __future__ import with_statement
2
+ import datetime
3
+ import os
4
+ import sys
5
+ import unittest
6
+
7
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
8
+ import pyotp
9
+
10
+
11
+ class HOTPExampleValuesFromTheRFC(unittest.TestCase):
12
+ def testMatchTheRFC(self):
13
+ # 12345678901234567890 in Bas32
14
+ # GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ
15
+ hotp = pyotp.HOTP('GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ')
16
+ self.assertEqual(hotp.at(0), 755224)
17
+ self.assertEqual(hotp.at(1), 287082)
18
+ self.assertEqual(hotp.at(2), 359152)
19
+ self.assertEqual(hotp.at(3), 969429)
20
+ self.assertEqual(hotp.at(4), 338314)
21
+ self.assertEqual(hotp.at(5), 254676)
22
+ self.assertEqual(hotp.at(6), 287922)
23
+ self.assertEqual(hotp.at(7), 162583)
24
+ self.assertEqual(hotp.at(8), 399871)
25
+ self.assertEqual(hotp.at(9), 520489)
26
+
27
+ def testVerifyAnOTPAndNowAllowReuse(self):
28
+ hotp = pyotp.HOTP('GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ')
29
+ self.assertTrue(hotp.verify(520489, 9))
30
+ self.assertFalse(hotp.verify(520489, 10))
31
+
32
+ def testProvisioningURI(self):
33
+ hotp = pyotp.HOTP('wrn3pqx5uqxqvnqr')
34
+ self.assertEqual(hotp.provisioning_uri('mark@percival'), 'otpauth://hotp/mark@percival?secret=wrn3pqx5uqxqvnqr&counter=0')
35
+
36
+
37
+ class TOTPExampleValuesFromTheRFC(unittest.TestCase):
38
+ def testMatchTheRFC(self):
39
+ totp = pyotp.TOTP('GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ')
40
+ self.assertEqual(totp.at(1111111111), 50471)
41
+ self.assertEqual(totp.at(1234567890), 5924)
42
+ self.assertEqual(totp.at(2000000000), 279037)
43
+
44
+ def testMatchTheGoogleAuthenticatorOutput(self):
45
+ totp = pyotp.TOTP('wrn3pqx5uqxqvnqr')
46
+ with Timecop(1297553958):
47
+ self.assertEqual(totp.now(), 102705)
48
+
49
+ def testValidateATimeBasedOTP(self):
50
+ totp = pyotp.TOTP('wrn3pqx5uqxqvnqr')
51
+ with Timecop(1297553958):
52
+ self.assertTrue(totp.verify(102705))
53
+ with Timecop(1297553958 + 30):
54
+ self.assertFalse(totp.verify(102705))
55
+
56
+ def testProvisioningURI(self):
57
+ totp = pyotp.TOTP('wrn3pqx5uqxqvnqr')
58
+ self.assertEqual(totp.provisioning_uri('mark@percival'), 'otpauth://totp/mark@percival?secret=wrn3pqx5uqxqvnqr')
59
+
60
+
61
+ class Timecop(object):
62
+ """
63
+ Half-assed clone of timecop.rb, just enough to pass our tests.
64
+ """
65
+
66
+ def __init__(self, freeze_timestamp):
67
+ self.freeze_timestamp = freeze_timestamp
68
+
69
+ def __enter__(self):
70
+ self.real_datetime = datetime.datetime
71
+ datetime.datetime = self.frozen_datetime()
72
+
73
+ def __exit__(self, type, value, traceback):
74
+ datetime.datetime = self.real_datetime
75
+
76
+ def frozen_datetime(self):
77
+ class FrozenDateTime(datetime.datetime):
78
+ @classmethod
79
+ def now(cls):
80
+ return cls.fromtimestamp(timecop.freeze_timestamp)
81
+
82
+ timecop = self
83
+ return FrozenDateTime
84
+
85
+
86
+ if __name__ == '__main__':
87
+ unittest.main()