Merge pull request #19 from kuba2k2/master
Add hebe Python implementation
This commit is contained in:
commit
ea2a17814a
9 changed files with 399 additions and 0 deletions
|
@ -56,6 +56,15 @@ jobs:
|
|||
path: ~/signer
|
||||
- run: pip install --user .[testing]
|
||||
- run: python -m pytest .
|
||||
python-hebe:
|
||||
working_directory: ~/signer/hebe-python
|
||||
docker:
|
||||
- image: circleci/python:3.8
|
||||
steps:
|
||||
- checkout:
|
||||
path: ~/signer
|
||||
- run: pip install --user .[testing]
|
||||
- run: python -m pytest .
|
||||
|
||||
dotnet:
|
||||
working_directory: ~/signer/dotnet
|
||||
|
@ -86,5 +95,6 @@ workflows:
|
|||
- jvm
|
||||
- jvm-hebe
|
||||
- python
|
||||
- python-hebe
|
||||
- dotnet
|
||||
- dart-hebe
|
||||
|
|
|
@ -20,6 +20,7 @@
|
|||
|---|---|
|
||||
| [Node.js](https://github.com/wulkanowy/uonet-request-signer/tree/master/hebe-node) | [![npm](https://img.shields.io/npm/v/@wulkanowy/uonet-request-signer-node-hebe.svg?style=flat-square)](https://www.npmjs.com/package/@wulkanowy/uonet-request-signer-node-hebe) |
|
||||
| [JVM](https://github.com/wulkanowy/uonet-request-signer/tree/master/hebe-jvm) | [![JitPack](https://img.shields.io/jitpack/v/wulkanowy/uonet-request-signer.svg?style=flat-square)](https://jitpack.io/#wulkanowy/uonet-request-signer) |
|
||||
| [Python](https://github.com/wulkanowy/uonet-request-signer/tree/master/hebe-python) | [![pypi](https://img.shields.io/pypi/v/uonet-request-signer-hebe.svg?style=flat-square)](https://pypi.org/project/uonet-request-signer-hebe/) |
|
||||
| [Dart](https://github.com/wulkanowy/uonet-request-signer/tree/master/hebe-dart) | [![pub](https://img.shields.io/pub/v/uonet_request_signer?style=flat-square)](https://pub.dev/packages/uonet_request_signer) |
|
||||
|
||||
|
||||
|
|
155
hebe-python/.gitignore
vendored
Normal file
155
hebe-python/.gitignore
vendored
Normal file
|
@ -0,0 +1,155 @@
|
|||
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/python,vscode
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=python,vscode
|
||||
|
||||
### Python ###
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
pip-wheel-metadata/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
pytestdebug.log
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
doc/_build/
|
||||
|
||||
# PyBuilder
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
pythonenv*
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# profiling data
|
||||
.prof
|
||||
|
||||
### vscode ###
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
*.code-workspace
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/python,vscode
|
||||
|
||||
*.pem*
|
21
hebe-python/LICENSE
Normal file
21
hebe-python/LICENSE
Normal file
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2020 Wulkanowy
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
24
hebe-python/README.md
Normal file
24
hebe-python/README.md
Normal file
|
@ -0,0 +1,24 @@
|
|||
# UONET+ (hebe) request signer for Python
|
||||
|
||||
[![pypi](https://img.shields.io/pypi/v/uonet-request-signer-hebe.svg?style=flat-square)](https://pypi.org/project/uonet-request-signer-hebe/)
|
||||
|
||||
## Installation
|
||||
|
||||
```console
|
||||
$ pip install -U uonet-request-signer-hebe
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```python
|
||||
from uonet_request_signer_hebe import get_signature_values
|
||||
from datetime import datetime
|
||||
|
||||
digest, canonical_url, signature = get_signature_values(fingerprint, private_key, body, full_url, datetime.now())
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
```console
|
||||
$ python -m pytest .
|
||||
```
|
39
hebe-python/setup.py
Normal file
39
hebe-python/setup.py
Normal file
|
@ -0,0 +1,39 @@
|
|||
import setuptools
|
||||
import re
|
||||
|
||||
with open("README.md") as f:
|
||||
long_description = f.read()
|
||||
|
||||
with open("uonet_request_signer_hebe/__init__.py") as f:
|
||||
text = f.read()
|
||||
__name__ = re.search(r"__name__ = \"(.*?)\"", text)[1]
|
||||
__version__ = re.search(r"__version__ = \"(.*?)\"", text)[1]
|
||||
|
||||
setuptools.setup(
|
||||
name=__name__,
|
||||
version=__version__,
|
||||
description="UONET+ (hebe) request signer for Python",
|
||||
long_description=long_description,
|
||||
long_description_content_type="text/markdown",
|
||||
url="https://github.com/wulkanowy/uonet-request-signer",
|
||||
author="Wulkanowy",
|
||||
author_email="wulkanowyinc@gmail.com",
|
||||
maintainer="Kuba Szczodrzyński",
|
||||
maintainer_email="kuba@szczodrzynski.pl",
|
||||
license="MIT",
|
||||
classifiers=[
|
||||
"Development Status :: 4 - Beta",
|
||||
"Intended Audience :: Developers",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Natural Language :: English",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Topic :: Education",
|
||||
"Topic :: Internet :: WWW/HTTP",
|
||||
"Topic :: Security :: Cryptography",
|
||||
"Topic :: Software Development :: Libraries :: Python Modules",
|
||||
],
|
||||
packages=setuptools.find_packages(),
|
||||
install_requires=["pyopenssl"],
|
||||
extras_require={"testing": ["pytest"]},
|
||||
)
|
61
hebe-python/tests/test_signer.py
Normal file
61
hebe-python/tests/test_signer.py
Normal file
|
@ -0,0 +1,61 @@
|
|||
from uonet_request_signer_hebe import get_signature_values
|
||||
import pytest
|
||||
from datetime import datetime, timezone
|
||||
|
||||
fingerprint = "7EBA57E1DDBA1C249D097A9FF1C9CCDD45351A6A"
|
||||
private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDCbF5Tt176EpB4cX5U+PZE0XytjJ9ABDZFaBFDkaexbkuNeuLOaARjQEOlUoBmpZQXxAF8HlYqeTvPiTcnSfQIS6EdqpICuQNdwvy6CHFAe2imkbbB0aHPsGep6zH8ZxHbssazkTCnGy0j2ZtGT2/iy1GEvc/p2bOkCVcR1H1GqFp+/XpfaMwi2SRCwc67K8Fu8TjSDKNvcRT9nuenGoPA1CWoOi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XNIRoVU/MXUkcV1m/3wRGV119M4IAbHFnQdbO0N8kaMTmwS4DxYzh0LzbHMM+JpGtPgDENRx3unWD/aYZzuvQnnQP3O9n7Kh46BwNQRWUMamL3+tY8n83WZwhqC4QKBgBTUzHy0sEEZ3hYgwU2ygbzC0vPladw2KqtKy+0LdHtx5pqE4/pvhVMpRRTNBDiAvb5lZmMB/B3CzoiMQOwczuus8Xsx7bEci28DzQ+g2zt0/bC2Xl+992Ass5PP5NtOrP/9QiTNgoFSCrVnZnNzQqpjCrFsjfOD2fiuFLCD6zi6"
|
||||
body = "{}"
|
||||
full_url = "/powiatwulkanowy/123456/api/mobile/register/hebe"
|
||||
timestamp = datetime(2020, 4, 14, 4, 14, 16)
|
||||
|
||||
expected_digest = "SHA-256=RBNvo1WzZ4oRRq0W9+hknpT7T8If536DEMBg9hyq/4o="
|
||||
expected_canonical_url = "api%2fmobile%2fregister%2fhebe"
|
||||
expected_signature = ','.join([
|
||||
'keyId="7EBA57E1DDBA1C249D097A9FF1C9CCDD45351A6A"',
|
||||
'headers="vCanonicalUrl Digest vDate"',
|
||||
'algorithm="sha256withrsa"',
|
||||
'signature=Base64(SHA256withRSA(mIVNkthTzTHmmXG1qxv1Jpt3uRlyhbj7VHysbCNpl0zXCCzuwTXsuCrfjexDDXsyJVo/LznQKOyvOaW4tEfrBobxtbtTnp7zYi54bdvAZa3pvM02yvkH4i/DvTLDKRO0R9UDZ1LraGrOTsIe3m3mQ21NOynVqCKadeqod8Y7l4YUlVYEmrtq/7xbCwr0qdne6G67eY4Amj6ffbG3TkVLpUrEETBnAC7oFjGYKhcRyvltAi+lcv6omANz1gwELf+Vmsa8NwFo/YGwY3R23z15athU/1iC1JcrECBLC8nRM1+KlvyIqx2HX6RG5R1cMOwBWVg6pRKUdrhxYbQ+VQ8Cag==))'
|
||||
])
|
||||
expected_signature_no_body = ','.join([
|
||||
'keyId="7EBA57E1DDBA1C249D097A9FF1C9CCDD45351A6A"',
|
||||
'headers="vCanonicalUrl vDate"',
|
||||
'algorithm="sha256withrsa"',
|
||||
'signature=Base64(SHA256withRSA(An1Fkg2OjCNOjGMJRG/YmAGGsqzXT00kkRaLq54U30LS8B9yf6f1wjumg4tCxi3x6aGrnf7pKiuhQgHTAbBAGJzwIBGrVcch24pBTPHfZsibOiNJVNu0s6wP8wCDq97JRCUCti9kyt8hcIZiicOVL+wDgV6NAFYkloAKTdEUBC6tqeFObgktr4Qhxa/khKtD4/hwKTSEJFIQKFtOlAuekXFNafdQwekFFmXtKNd69b1n3p39XVHe0bM5AJVNr0kMvN6M97/8RE4Tz62CXKUVla6XyY7n+osrFMnTAGGtXq15FjS3UI6ObUmx9dHJHREn2GdB1DY3KCCv46O1zaRq4A==))'
|
||||
])
|
||||
|
||||
TEST_DATA = [
|
||||
( # with a POST body
|
||||
fingerprint,
|
||||
private_key,
|
||||
body,
|
||||
full_url,
|
||||
timestamp,
|
||||
expected_digest,
|
||||
expected_canonical_url,
|
||||
expected_signature
|
||||
),
|
||||
( # without a POST body
|
||||
fingerprint,
|
||||
private_key,
|
||||
None, # body
|
||||
full_url,
|
||||
timestamp,
|
||||
None, # digest
|
||||
expected_canonical_url,
|
||||
expected_signature_no_body
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def test_invalid_url():
|
||||
with pytest.raises(ValueError):
|
||||
get_signature_values('', '', '', 'invalid url', datetime.now())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fingerprint,private_key,body,full_url,timestamp,expected_digest,expected_canonical_url,expected_signature", TEST_DATA)
|
||||
def test_signature(fingerprint, private_key, body, full_url, timestamp, expected_digest, expected_canonical_url, expected_signature):
|
||||
digest, canonical_url, signature = get_signature_values(fingerprint, private_key, body, full_url, timestamp)
|
||||
|
||||
assert expected_digest == digest
|
||||
assert expected_canonical_url == canonical_url
|
||||
assert expected_signature == signature
|
6
hebe-python/uonet_request_signer_hebe/__init__.py
Normal file
6
hebe-python/uonet_request_signer_hebe/__init__.py
Normal file
|
@ -0,0 +1,6 @@
|
|||
from .signer import get_signature_values
|
||||
|
||||
__name__ = "uonet-request-signer-hebe"
|
||||
__version__ = "0.1.0"
|
||||
|
||||
__all__ = ["get_signature_values"]
|
82
hebe-python/uonet_request_signer_hebe/signer.py
Normal file
82
hebe-python/uonet_request_signer_hebe/signer.py
Normal file
|
@ -0,0 +1,82 @@
|
|||
from OpenSSL import crypto
|
||||
import hashlib
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import urllib
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def get_encoded_path(full_url):
|
||||
path = re.search(r'(api/mobile/.+)', full_url)
|
||||
if path is None:
|
||||
raise ValueError('The URL does not seem correct (does not match `(api/mobile/.+)` regex)')
|
||||
return urllib.parse.quote(path[1], safe='').lower()
|
||||
|
||||
|
||||
def get_digest(body):
|
||||
if not body:
|
||||
return None
|
||||
|
||||
m = hashlib.sha256()
|
||||
m.update(bytes(body, 'utf-8'))
|
||||
return base64.b64encode(m.digest()).decode('utf-8')
|
||||
|
||||
|
||||
def get_headers_list(body, digest, canonical_url, timestamp):
|
||||
sign_data = [
|
||||
['vCanonicalUrl', canonical_url],
|
||||
['Digest', digest] if body else None,
|
||||
['vDate', timestamp.strftime('%a, %d %b %Y %H:%M:%S GMT')]
|
||||
]
|
||||
|
||||
return (
|
||||
' '.join(item[0] for item in sign_data if item),
|
||||
''.join(item[1] for item in sign_data if item)
|
||||
)
|
||||
|
||||
|
||||
def get_signature(data, private_key):
|
||||
data_str = json.dumps(data) if isinstance(data, dict) or isinstance(data, list) else str(data)
|
||||
pkcs8 = crypto.load_privatekey(crypto.FILETYPE_ASN1, base64.b64decode(private_key))
|
||||
signature = crypto.sign(pkcs8, bytes(data_str, 'utf-8'), 'RSA-SHA256')
|
||||
return base64.b64encode(signature).decode('utf-8')
|
||||
|
||||
|
||||
def get_signature_values(fingerprint, private_key, body, full_url, timestamp):
|
||||
canonical_url = get_encoded_path(full_url)
|
||||
digest = get_digest(body)
|
||||
headers, values = get_headers_list(body, digest, canonical_url, timestamp)
|
||||
signature = get_signature(values, private_key)
|
||||
|
||||
return (
|
||||
f'SHA-256={digest}' if digest else None,
|
||||
canonical_url,
|
||||
f'keyId="{fingerprint}",headers="{headers}",algorithm="sha256withrsa",signature=Base64(SHA256withRSA({signature}))'
|
||||
)
|
||||
|
||||
|
||||
def pem_getraw(pem):
|
||||
return pem.decode('utf-8').replace('\n', '').split('-----')[2]
|
||||
|
||||
|
||||
def generate_key_pair():
|
||||
pkcs8 = crypto.PKey()
|
||||
pkcs8.generate_key(crypto.TYPE_RSA, 2048)
|
||||
|
||||
x509 = crypto.X509()
|
||||
x509.set_version(2)
|
||||
x509.set_serial_number(1)
|
||||
subject = x509.get_subject()
|
||||
subject.CN = "APP_CERTIFICATE CA Certificate"
|
||||
x509.set_issuer(subject)
|
||||
x509.set_pubkey(pkcs8)
|
||||
x509.sign(pkcs8, 'sha256')
|
||||
x509.gmtime_adj_notBefore(0)
|
||||
x509.gmtime_adj_notAfter(20*365*24*60*60)
|
||||
|
||||
certificate = pem_getraw(crypto.dump_certificate(crypto.FILETYPE_PEM, x509))
|
||||
fingerprint = x509.digest('sha1').decode('utf-8').replace(':', '').lower()
|
||||
private_key = pem_getraw(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs8))
|
||||
|
||||
return certificate, fingerprint, private_key
|
Loading…
Reference in a new issue