Name | Flask-RSA JSON |
Version |
0.2.2
JSON |
| download |
home_page | https://github.com/mwalkowski/flask-rsa |
Summary | This Flask extension provides server-side implementation of RSA-based request signature validation. |
upload_time | 2024-09-04 08:29:47 |
maintainer | None |
docs_url | None |
author | mwalkowski |
requires_python | >=3.8 |
license | MIT License Copyright (c) 2024 Michał Walkowski 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. |
keywords |
flask
rsa
rest
views
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
[![security: bandit](https://img.shields.io/badge/security-bandit-yellow.svg)](https://github.com/PyCQA/bandit)![example workflow](https://github.com/mwalkowski/flask-rsa/actions/workflows/python-package.yml/badge.svg)![PyPI - Downloads](https://img.shields.io/pypi/dm/flask-rsa)
# Flask RSA
This Flask extension provides server-side implementation of RSA-based request signature validation, encryption, and decryption. It enhances the security of web applications by ensuring the integrity, authenticity, and confidentiality of incoming requests and outgoing responses.
## Installation
Install the Flask RSA extension using pip:
```bash
pip install flask-rsa
```
## Usage
To use this extension in your Flask application, follow these steps:
1. Import the RSA class from the flask_rsa module.
```python
from flask_rsa import RSA
```
2. Create a Flask application and initialize the RSA extension.
```python
from flask import Flask
app = Flask(__name__)
rsa = RSA(app)
```
3.Decorate the route(s) that require RSA signature validation using the `@rsa.signature_required()` decorator.
```python
@app.route('/secure-endpoint', methods=['POST'])
@rsa.signature_required()
def secure_endpoint():
# Your protected route logic here
return jsonify({"message": "Request successfully validated and processed"})
```
4.(Optional) Decorate the route(s) that require RSA request body decryption using the `@rsa.encrypted_request()` decorator:
```python
@app.route('/encrypted-endpoint', methods=['POST'])
@rsa.encrypted_request()
def encrypted_request_endpoint(request_body):
# Your encrypted route logic here
return jsonify({"message": "Request successfully decrypted and processed"})
```
5.(Optional) Decorate the route(s) that require RSA response body encryption using the `@rsa.encrypted_response()` decorator:
```python
@app.route('/encrypted-endpoint', methods=['POST'])
@rsa.encrypted_response()
def encrypted_endpoint():
# Your encrypted route logic here
return jsonify({"message": "Response successfully encrypted and sent"})
```
6.(Optional) Decorate the route(s) that require RSA request body decryption, response body encryption, and signature validation using the flowing example:
```python
@app.route('/encrypted-endpoint', methods=['POST'])
@rsa.signature_required()
@rsa.encrypted_request()
@rsa.encrypted_response()
def encrypted_endpoint():
# Your encrypted route logic here
return jsonify({"message": "Response successfully encrypted and sent"})
```
7.(Optional) Customize the extension by adjusting the configuration parameters.
```python
app.config['RSA_SIGNATURE_HEADER'] = 'X-Signature'
app.config['RSA_NONCE_HEADER'] = 'X-Nonce-Value'
# Add more configuration parameters as needed
```
5. Run your Flask application as usual.
## Configuration Parameters
* `RSA_SIGNATURE_HEADER`: Header name for the RSA signature (default: `X-Signature`).
* `RSA_NONCE_HEADER`: Header name for the nonce value (default: `X-Nonce-Value`).
* `RSA_NONCE_CREATED_AT_HEADER`: Header name for the nonce creation timestamp (default: `X-Nonce-Created-At`).
* `RSA_NONCE_QUEUE_SIZE_LIMIT`: Limit on the number of nonces stored in the queue (default: 10).
* `RSA_TIME_DIFF_TOLERANCE_IN_SECONDS`: Time difference tolerance for nonce validation (default: 10.0 seconds).
* `RSA_PUBLIC_KEY_URL`: Endpoint URL for exposing the server's public key (default: `/public-key`).
* `RSA_PRIVATE_KEY_PATH` and `RSA_PUBLIC_KEY_PATH`: Paths to the private and public keys, respectively. If not provided, new keys will be generated.
* `RSA_ERROR_CODE`: HTTP status code to return in case of validation failure (default: 403).
* `RSA_PAYLOAD_PLACEHOLDER`: Placeholder for encrypted payload in request/response (default: `PAYLOAD_PLACEHOLDER`).
* `RSA_ENCRYPTED_PAYLOAD_KEY`: Key name for encrypted payload in request/response (default: `encrypted_payload`).
* `RSA_ENCRYPTED_PAYLOAD_STRUCTURE`: Structure for encrypted payload in request/response (default: ```{'encrypted_payload': 'PAYLOAD_PLACEHOLDER'}```).
## Example
For a practical example of how to use this extension, refer to the provided [example code](./examples).
### User Key Verification Extension
For additional user key verification, extend the RSA class:
```python
from flask_rsa import RSA as FlaskRsa
class RSA(FlaskRsa):
def _get_user_public_key(self, request):
return FlaskRsa._load_public_key(request.current_user.public_key.encode())
```
More code can be found in the [example/server.py](./examples/server.py) file.
### Signature Generation
To generate an RSA signature, use the create_signature_input and generate_signature functions:
```python
def create_signature_input(nonce_created_at, nonce_value, path, method, request_body):
signature_input = (F"{method}{path}{nonce_value}"
F"{nonce_created_at}{request_body}")
signature_input_b64 = base64.standard_b64encode(signature_input.encode())
return signature_input_b64
def generate_signature(private_key, signature_input_b64):
return base64.standard_b64encode(private_key.sign(
signature_input_b64,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256())
).decode('utf-8')
```
### Signature Addition
To add an RSA signature to headers, use the add_signature function:
```python
def add_signature(headers, method, path, request_body, private_key):
nonce = str(uuid.uuid4())
nonce_created_at = datetime.now(timezone.utc).isoformat()
signature_input_b64 = create_signature_input(nonce_created_at, nonce, path, method,
request_body)
headers[SIGNATURE_HEADER] = generate_signature(private_key, signature_input_b64)
headers[NONCE_HEADER] = nonce
headers[NONCE_CREATED_AT_HEADER] = nonce_created_at
return headers
```
### Signature Verification
To verify an RSA signature, use the verify function:
```python
def verify(server_public_key, signature_input_b64, received_signature):
try:
server_public_key.verify(
base64.standard_b64decode(received_signature),
signature_input_b64,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
except InvalidSignature:
return False
return True
```
### Encryption
To encrypt request body, use the encrypt function:
```python
def encrypt(body, server_public_key):
return base64.standard_b64encode(server_public_key.encrypt(
base64.standard_b64encode(body.encode('utf-8')),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)).decode()
```
### Decryption
To decrypt response body, use the decrypt function:
```python
def decrypt(data, private_key):
return base64.standard_b64decode(private_key.decrypt(
base64.standard_b64decode(data),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
))
```
More code can be found in the [example/client.py](./examples/client.py) file.
## License
This extension is released under the MIT License. See the [LICENSE](./LICENSE) file for more details.
Raw data
{
"_id": null,
"home_page": "https://github.com/mwalkowski/flask-rsa",
"name": "Flask-RSA",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "Flask, RSA, REST, Views",
"author": "mwalkowski",
"author_email": "Michal Walkowski <michal.walkowski@pwr.edu.pl>",
"download_url": "https://files.pythonhosted.org/packages/37/95/4c97922249d6ef34e5d8a9b029b2854ecf3cac943f3238e823c1593e2888/flask_rsa-0.2.2.tar.gz",
"platform": null,
"description": "[![security: bandit](https://img.shields.io/badge/security-bandit-yellow.svg)](https://github.com/PyCQA/bandit)![example workflow](https://github.com/mwalkowski/flask-rsa/actions/workflows/python-package.yml/badge.svg)![PyPI - Downloads](https://img.shields.io/pypi/dm/flask-rsa)\n\n\n# Flask RSA\nThis Flask extension provides server-side implementation of RSA-based request signature validation, encryption, and decryption. It enhances the security of web applications by ensuring the integrity, authenticity, and confidentiality of incoming requests and outgoing responses.\n\n## Installation\nInstall the Flask RSA extension using pip:\n\n```bash\npip install flask-rsa\n```\n\n## Usage\nTo use this extension in your Flask application, follow these steps:\n\n1. Import the RSA class from the flask_rsa module.\n\n```python\nfrom flask_rsa import RSA\n```\n2. Create a Flask application and initialize the RSA extension.\n\n```python\nfrom flask import Flask\n\napp = Flask(__name__)\nrsa = RSA(app)\n```\n\n3.Decorate the route(s) that require RSA signature validation using the `@rsa.signature_required()` decorator.\n```python\n@app.route('/secure-endpoint', methods=['POST'])\n@rsa.signature_required()\ndef secure_endpoint():\n # Your protected route logic here\n return jsonify({\"message\": \"Request successfully validated and processed\"})\n```\n\n4.(Optional) Decorate the route(s) that require RSA request body decryption using the `@rsa.encrypted_request()` decorator:\n```python\n@app.route('/encrypted-endpoint', methods=['POST'])\n@rsa.encrypted_request()\ndef encrypted_request_endpoint(request_body):\n # Your encrypted route logic here\n return jsonify({\"message\": \"Request successfully decrypted and processed\"})\n```\n\n5.(Optional) Decorate the route(s) that require RSA response body encryption using the `@rsa.encrypted_response()` decorator:\n```python\n@app.route('/encrypted-endpoint', methods=['POST'])\n@rsa.encrypted_response()\ndef encrypted_endpoint():\n # Your encrypted route logic here\n return jsonify({\"message\": \"Response successfully encrypted and sent\"})\n```\n\n6.(Optional) Decorate the route(s) that require RSA request body decryption, response body encryption, and signature validation using the flowing example:\n```python\n@app.route('/encrypted-endpoint', methods=['POST'])\n@rsa.signature_required()\n@rsa.encrypted_request()\n@rsa.encrypted_response()\ndef encrypted_endpoint():\n # Your encrypted route logic here\n return jsonify({\"message\": \"Response successfully encrypted and sent\"})\n```\n\n7.(Optional) Customize the extension by adjusting the configuration parameters.\n```python\napp.config['RSA_SIGNATURE_HEADER'] = 'X-Signature'\napp.config['RSA_NONCE_HEADER'] = 'X-Nonce-Value'\n# Add more configuration parameters as needed\n```\n5. Run your Flask application as usual.\n\n## Configuration Parameters\n* `RSA_SIGNATURE_HEADER`: Header name for the RSA signature (default: `X-Signature`).\n* `RSA_NONCE_HEADER`: Header name for the nonce value (default: `X-Nonce-Value`).\n* `RSA_NONCE_CREATED_AT_HEADER`: Header name for the nonce creation timestamp (default: `X-Nonce-Created-At`).\n* `RSA_NONCE_QUEUE_SIZE_LIMIT`: Limit on the number of nonces stored in the queue (default: 10).\n* `RSA_TIME_DIFF_TOLERANCE_IN_SECONDS`: Time difference tolerance for nonce validation (default: 10.0 seconds).\n* `RSA_PUBLIC_KEY_URL`: Endpoint URL for exposing the server's public key (default: `/public-key`).\n* `RSA_PRIVATE_KEY_PATH` and `RSA_PUBLIC_KEY_PATH`: Paths to the private and public keys, respectively. If not provided, new keys will be generated.\n* `RSA_ERROR_CODE`: HTTP status code to return in case of validation failure (default: 403).\n* `RSA_PAYLOAD_PLACEHOLDER`: Placeholder for encrypted payload in request/response (default: `PAYLOAD_PLACEHOLDER`).\n* `RSA_ENCRYPTED_PAYLOAD_KEY`: Key name for encrypted payload in request/response (default: `encrypted_payload`).\n* `RSA_ENCRYPTED_PAYLOAD_STRUCTURE`: Structure for encrypted payload in request/response (default: ```{'encrypted_payload': 'PAYLOAD_PLACEHOLDER'}```).\n\n## Example\n\nFor a practical example of how to use this extension, refer to the provided [example code](./examples).\n\n### User Key Verification Extension\nFor additional user key verification, extend the RSA class:\n```python\nfrom flask_rsa import RSA as FlaskRsa\n\nclass RSA(FlaskRsa):\n def _get_user_public_key(self, request):\n return FlaskRsa._load_public_key(request.current_user.public_key.encode())\n```\n\nMore code can be found in the [example/server.py](./examples/server.py) file.\n\n### Signature Generation\nTo generate an RSA signature, use the create_signature_input and generate_signature functions:\n```python\ndef create_signature_input(nonce_created_at, nonce_value, path, method, request_body):\n signature_input = (F\"{method}{path}{nonce_value}\"\n F\"{nonce_created_at}{request_body}\")\n signature_input_b64 = base64.standard_b64encode(signature_input.encode())\n return signature_input_b64\n\ndef generate_signature(private_key, signature_input_b64):\n return base64.standard_b64encode(private_key.sign(\n signature_input_b64,\n padding.PSS(\n mgf=padding.MGF1(hashes.SHA256()),\n salt_length=padding.PSS.MAX_LENGTH\n ),\n hashes.SHA256())\n ).decode('utf-8')\n```\n\n### Signature Addition\nTo add an RSA signature to headers, use the add_signature function:\n```python\ndef add_signature(headers, method, path, request_body, private_key):\n nonce = str(uuid.uuid4())\n nonce_created_at = datetime.now(timezone.utc).isoformat()\n signature_input_b64 = create_signature_input(nonce_created_at, nonce, path, method,\n request_body)\n headers[SIGNATURE_HEADER] = generate_signature(private_key, signature_input_b64)\n headers[NONCE_HEADER] = nonce\n headers[NONCE_CREATED_AT_HEADER] = nonce_created_at\n return headers\n```\n\n### Signature Verification\nTo verify an RSA signature, use the verify function:\n```python\ndef verify(server_public_key, signature_input_b64, received_signature):\n try:\n server_public_key.verify(\n base64.standard_b64decode(received_signature),\n signature_input_b64,\n padding.PSS(\n mgf=padding.MGF1(hashes.SHA256()),\n salt_length=padding.PSS.MAX_LENGTH\n ),\n hashes.SHA256()\n )\n except InvalidSignature:\n return False\n return True\n```\n\n### Encryption\nTo encrypt request body, use the encrypt function:\n```python\ndef encrypt(body, server_public_key):\n return base64.standard_b64encode(server_public_key.encrypt(\n base64.standard_b64encode(body.encode('utf-8')),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )).decode()\n```\n\n### Decryption\nTo decrypt response body, use the decrypt function:\n```python\ndef decrypt(data, private_key):\n return base64.standard_b64decode(private_key.decrypt(\n base64.standard_b64decode(data),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n ))\n```\nMore code can be found in the [example/client.py](./examples/client.py) file.\n\n## License\nThis extension is released under the MIT License. See the [LICENSE](./LICENSE) file for more details.\n",
"bugtrack_url": null,
"license": "MIT License Copyright (c) 2024 Micha\u0142 Walkowski 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. ",
"summary": "This Flask extension provides server-side implementation of RSA-based request signature validation.",
"version": "0.2.2",
"project_urls": {
"Homepage": "https://github.com/mwalkowski/flask-rsa",
"Issues": "https://github.com/mwalkowski/flask-rsa/issues"
},
"split_keywords": [
"flask",
" rsa",
" rest",
" views"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "5eda0f827ccb918b0b11bc5a4aa913653b07e5af19265b9a8db97e90d4c7df6f",
"md5": "f30f9979b99d5841be705e790562e7dd",
"sha256": "7f7c397ddc5fd5fa2e023c4fdb643dcba90ba3923ffacb49270be2976582c04b"
},
"downloads": -1,
"filename": "Flask_RSA-0.2.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "f30f9979b99d5841be705e790562e7dd",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 8298,
"upload_time": "2024-09-04T08:29:46",
"upload_time_iso_8601": "2024-09-04T08:29:46.742981Z",
"url": "https://files.pythonhosted.org/packages/5e/da/0f827ccb918b0b11bc5a4aa913653b07e5af19265b9a8db97e90d4c7df6f/Flask_RSA-0.2.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "37954c97922249d6ef34e5d8a9b029b2854ecf3cac943f3238e823c1593e2888",
"md5": "6d62bad1dd4e544d5f927779a371105b",
"sha256": "5e5822de5f15ecb28ad147ca23367a8ed97cdad9d6a8b1d3f006b2e488b978fd"
},
"downloads": -1,
"filename": "flask_rsa-0.2.2.tar.gz",
"has_sig": false,
"md5_digest": "6d62bad1dd4e544d5f927779a371105b",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 10624,
"upload_time": "2024-09-04T08:29:47",
"upload_time_iso_8601": "2024-09-04T08:29:47.814438Z",
"url": "https://files.pythonhosted.org/packages/37/95/4c97922249d6ef34e5d8a9b029b2854ecf3cac943f3238e823c1593e2888/flask_rsa-0.2.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-09-04 08:29:47",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "mwalkowski",
"github_project": "flask-rsa",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [],
"test_requirements": [],
"tox": true,
"lcname": "flask-rsa"
}