apsig 0.1.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.
- apsig-0.1.0/LICENSE +21 -0
- apsig-0.1.0/PKG-INFO +17 -0
- apsig-0.1.0/README.md +4 -0
- apsig-0.1.0/pyproject.toml +30 -0
- apsig-0.1.0/src/http_signactures/__init__.py +7 -0
- apsig-0.1.0/src/http_signactures/__polyfill/datetime.py +9 -0
- apsig-0.1.0/src/http_signactures/__polyfill/jsonld.py +31 -0
- apsig-0.1.0/src/http_signactures/draft/sign.py +34 -0
- apsig-0.1.0/src/http_signactures/draft/verify.py +72 -0
- apsig-0.1.0/src/http_signactures/ld/ldsig.py +58 -0
- apsig-0.1.0/src/http_signactures/object_integrity_proofs/sign.py +41 -0
- apsig-0.1.0/src/http_signactures/object_integrity_proofs/verify.py +85 -0
- apsig-0.1.0/tests/__init__.py +0 -0
- apsig-0.1.0/tests/test_draft.py +71 -0
- apsig-0.1.0/tests/test_ld.py +57 -0
- apsig-0.1.0/tests/test_oip.py +77 -0
apsig-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Holo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
apsig-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: apsig
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Signature implementation used in ActivityPub.
|
|
5
|
+
Author-Email: AmaseCocoa <amase.cocoa@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: cryptography>=43.0.1
|
|
9
|
+
Requires-Dist: pynacl>=1.5.0
|
|
10
|
+
Requires-Dist: pyld>=2.0.4
|
|
11
|
+
Requires-Dist: aiohttp>=3.10.5
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# apsig
|
|
15
|
+
Signature implementation used in ActivityPub.
|
|
16
|
+
|
|
17
|
+
This library implements the creation/verification of signatures for HTTP Signatures (draft-cavage-http-signatures-12), Linked Data Signatures, and Object Integrity Proofs (FEP-8b32).
|
apsig-0.1.0/README.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "apsig"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Signature implementation used in ActivityPub."
|
|
5
|
+
authors = [
|
|
6
|
+
{ name = "AmaseCocoa", email = "amase.cocoa@gmail.com" },
|
|
7
|
+
]
|
|
8
|
+
dependencies = [
|
|
9
|
+
"cryptography>=43.0.1",
|
|
10
|
+
"pynacl>=1.5.0",
|
|
11
|
+
"pyld>=2.0.4",
|
|
12
|
+
"aiohttp>=3.10.5",
|
|
13
|
+
]
|
|
14
|
+
requires-python = ">=3.10"
|
|
15
|
+
readme = "README.md"
|
|
16
|
+
|
|
17
|
+
[project.license]
|
|
18
|
+
text = "MIT"
|
|
19
|
+
|
|
20
|
+
[build-system]
|
|
21
|
+
requires = [
|
|
22
|
+
"pdm-backend",
|
|
23
|
+
]
|
|
24
|
+
build-backend = "pdm.backend"
|
|
25
|
+
|
|
26
|
+
[tool.pdm]
|
|
27
|
+
distribution = true
|
|
28
|
+
|
|
29
|
+
[tool.pdm.scripts]
|
|
30
|
+
test = "python test_runner.py"
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
from .object_integrity_proofs.sign import OIPSigner
|
|
2
|
+
from .object_integrity_proofs.verify import OIPVerifier
|
|
3
|
+
from .draft.sign import draftSigner
|
|
4
|
+
from .draft.verify import draftVerifier
|
|
5
|
+
from .ld.ldsig import JSONLDSigner
|
|
6
|
+
|
|
7
|
+
__all__ = ["OIPSigner", "OIPVerifier" , "draftSigner", "draftVerifier", "JSONLDSigner"]
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import datetime
|
|
3
|
+
|
|
4
|
+
def utcnow() -> datetime.datetime:
|
|
5
|
+
if sys.version_info < (3, 11):
|
|
6
|
+
return datetime.datetime.utcnow()
|
|
7
|
+
# The line `return datetimedatetime.now(datetime.UTC)` seems to have a typo. It should be
|
|
8
|
+
# corrected to `return datetime.datetime.now(datetime.timezone.utc)`.
|
|
9
|
+
return datetime.datetime.now(datetime.UTC)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
def load_json_ld(json_ld_str):
|
|
4
|
+
"""JSON-LD文字列を辞書型にロードする"""
|
|
5
|
+
return json.loads(json_ld_str)
|
|
6
|
+
|
|
7
|
+
def apply_context(data, context):
|
|
8
|
+
"""コンテキストを適用して、プレフィックスを解決する"""
|
|
9
|
+
if '@context' in data:
|
|
10
|
+
context.update(data['@context'])
|
|
11
|
+
expanded_data = {}
|
|
12
|
+
for key, value in data.items():
|
|
13
|
+
if key == '@context':
|
|
14
|
+
continue
|
|
15
|
+
expanded_key = expand_key(key, context)
|
|
16
|
+
expanded_data[expanded_key] = value
|
|
17
|
+
return expanded_data
|
|
18
|
+
|
|
19
|
+
def expand_key(key, context):
|
|
20
|
+
if key in context:
|
|
21
|
+
return context[key]
|
|
22
|
+
return key
|
|
23
|
+
|
|
24
|
+
def expand(data):
|
|
25
|
+
context = {}
|
|
26
|
+
if '@context' in data:
|
|
27
|
+
context = data['@context']
|
|
28
|
+
return apply_context(data, context)
|
|
29
|
+
|
|
30
|
+
def normalize(data):
|
|
31
|
+
return json.dumps(data, indent=2)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from cryptography.hazmat.primitives.asymmetric import padding
|
|
2
|
+
from cryptography.hazmat.primitives import hashes
|
|
3
|
+
from cryptography.hazmat.backends import default_backend
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
from urllib.parse import urlparse
|
|
7
|
+
|
|
8
|
+
class draftSigner:
|
|
9
|
+
def generate_digest(body):
|
|
10
|
+
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
|
|
11
|
+
digest.update(body.encode("utf-8"))
|
|
12
|
+
hash_bytes = digest.finalize()
|
|
13
|
+
return "SHA-256=" + base64.b64encode(hash_bytes).decode("utf-8")
|
|
14
|
+
|
|
15
|
+
def sign(private_key, method: str, url: str, headers: dict, key_id: str, body: bytes="") -> dict:
|
|
16
|
+
parsed_url = urlparse(url)
|
|
17
|
+
request_target = f"(request-target): {method.lower()} {parsed_url.path}"
|
|
18
|
+
|
|
19
|
+
digest = draftSigner.generate_digest(body)
|
|
20
|
+
headers["digest"] = digest
|
|
21
|
+
|
|
22
|
+
signature_headers = [request_target]
|
|
23
|
+
for header in headers:
|
|
24
|
+
signature_headers.append(f"{header}: {headers[header]}")
|
|
25
|
+
|
|
26
|
+
signature_string = "\n".join(signature_headers).encode("utf-8")
|
|
27
|
+
|
|
28
|
+
signature = private_key.sign(signature_string, padding.PKCS1v15(), hashes.SHA256())
|
|
29
|
+
signature_b64 = base64.b64encode(signature).decode("utf-8")
|
|
30
|
+
|
|
31
|
+
signature_header = f'keyId="{key_id}",algorithm="rsa-sha256",headers="(request-target) {" ".join(headers.keys())}",signature="{signature_b64}"'
|
|
32
|
+
headers["signature"] = signature_header
|
|
33
|
+
headers["Authorization"] = f"Signature {signature_header}" # Misskeyなどでは必要
|
|
34
|
+
return headers
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
from cryptography.hazmat.primitives.asymmetric import padding
|
|
2
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
3
|
+
from cryptography.hazmat.backends import default_backend
|
|
4
|
+
from cryptography.exceptions import InvalidSignature
|
|
5
|
+
|
|
6
|
+
import base64
|
|
7
|
+
import datetime
|
|
8
|
+
from urllib.parse import urlparse
|
|
9
|
+
|
|
10
|
+
class draftVerifier:
|
|
11
|
+
def generate_digest(body):
|
|
12
|
+
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
|
|
13
|
+
digest.update(body.encode("utf-8") if not isinstance(body, bytes) else body)
|
|
14
|
+
hash_bytes = digest.finalize()
|
|
15
|
+
return "SHA-256=" + base64.b64encode(hash_bytes).decode("utf-8")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def verify(public_pem: str, method: str, url: str, headers: dict, body: bytes=b""):
|
|
19
|
+
signature_header = headers.get("signature")
|
|
20
|
+
if not signature_header:
|
|
21
|
+
return False, "Signature header is missing"
|
|
22
|
+
|
|
23
|
+
signature_parts = {}
|
|
24
|
+
for item in signature_header.split(","):
|
|
25
|
+
key, value = item.split("=", 1)
|
|
26
|
+
signature_parts[key.strip()] = value.strip().strip('"')
|
|
27
|
+
|
|
28
|
+
signature = base64.b64decode(signature_parts["signature"])
|
|
29
|
+
keyId = signature_parts["keyId"]
|
|
30
|
+
algorithm = signature_parts["algorithm"]
|
|
31
|
+
|
|
32
|
+
if algorithm != "rsa-sha256":
|
|
33
|
+
return False, "Unsupported algorithm"
|
|
34
|
+
|
|
35
|
+
signed_headers = signature_parts["headers"].split()
|
|
36
|
+
|
|
37
|
+
parsed_url = urlparse(url)
|
|
38
|
+
request_target = f"(request-target): {method.lower()} {parsed_url.path}"
|
|
39
|
+
|
|
40
|
+
signature_headers = [request_target]
|
|
41
|
+
for header in signed_headers:
|
|
42
|
+
if header in headers:
|
|
43
|
+
signature_headers.append(f"{header}: {headers[header]}")
|
|
44
|
+
|
|
45
|
+
signature_string = "\n".join(signature_headers).encode("utf-8")
|
|
46
|
+
|
|
47
|
+
public_key = serialization.load_pem_public_key(
|
|
48
|
+
public_pem.encode('utf-8'),
|
|
49
|
+
backend=default_backend()
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
try:
|
|
53
|
+
public_key.verify(
|
|
54
|
+
signature, signature_string, padding.PKCS1v15(), hashes.SHA256()
|
|
55
|
+
)
|
|
56
|
+
except InvalidSignature:
|
|
57
|
+
return False, "Invalid signature"
|
|
58
|
+
|
|
59
|
+
expected_digest = draftVerifier.generate_digest(body)
|
|
60
|
+
if headers.get("digest") != expected_digest:
|
|
61
|
+
return False, "Digest mismatch"
|
|
62
|
+
|
|
63
|
+
date_header = headers.get("date")
|
|
64
|
+
if date_header:
|
|
65
|
+
request_time = datetime.datetime.strptime(
|
|
66
|
+
date_header, "%a, %d %b %Y %H:%M:%S GMT"
|
|
67
|
+
)
|
|
68
|
+
current_time = datetime.datetime.utcnow()
|
|
69
|
+
if abs((current_time - request_time).total_seconds()) > 3600:
|
|
70
|
+
return False, "Date header is too far from current time"
|
|
71
|
+
|
|
72
|
+
return True, "Signature is valid"
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# jsonld_signature.py
|
|
2
|
+
|
|
3
|
+
from pyld import jsonld
|
|
4
|
+
from nacl.signing import SigningKey
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import base64
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from email.utils import formatdate
|
|
10
|
+
from nacl.exceptions import BadSignatureError
|
|
11
|
+
from urllib.parse import urlparse
|
|
12
|
+
|
|
13
|
+
class JSONLDSigner:
|
|
14
|
+
def __init__(self):
|
|
15
|
+
self.signing_key = SigningKey.generate()
|
|
16
|
+
self.verify_key = self.signing_key.verify_key
|
|
17
|
+
|
|
18
|
+
def sign(self, data, headers, method: str, url: str, key_id: str):
|
|
19
|
+
normalized_data = jsonld.normalize(data, {'algorithm': 'URDNA2015', 'format': 'application/n-quads'})
|
|
20
|
+
|
|
21
|
+
date_header = formatdate(timeval=None, localtime=False, usegmt=True)
|
|
22
|
+
digest = 'SHA-256=' + base64.b64encode(hashlib.sha256(normalized_data.encode('utf-8')).digest()).decode()
|
|
23
|
+
parsed_url = urlparse(url)
|
|
24
|
+
|
|
25
|
+
headers['date'] = date_header
|
|
26
|
+
headers['digest'] = digest
|
|
27
|
+
headers['(request-target)'] = f'{method.lower()} {parsed_url.path}'
|
|
28
|
+
|
|
29
|
+
signed_headers = " ".join(headers.keys())
|
|
30
|
+
signature_base = "\n".join(f"{k}: {v}" for k, v in headers.items())
|
|
31
|
+
|
|
32
|
+
signature = self.signing_key.sign(signature_base.encode('utf-8'))
|
|
33
|
+
|
|
34
|
+
signature_header = {
|
|
35
|
+
'keyId': key_id,
|
|
36
|
+
'algorithm': 'hs2019',
|
|
37
|
+
'headers': signed_headers,
|
|
38
|
+
'signature': base64.b64encode(signature.signature).decode()
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return signature_header, normalized_data
|
|
42
|
+
|
|
43
|
+
def verify(self, signature_header, normalized_data, headers):
|
|
44
|
+
signature_bytes = base64.b64decode(signature_header['signature'])
|
|
45
|
+
signed_headers = signature_header['headers'].split()
|
|
46
|
+
if len(signature_bytes) != 64:
|
|
47
|
+
return False
|
|
48
|
+
headers['date'] = formatdate(timeval=None, localtime=False, usegmt=True)
|
|
49
|
+
digest = 'SHA-256=' + base64.b64encode(hashlib.sha256(normalized_data.encode('utf-8')).digest()).decode()
|
|
50
|
+
headers['digest'] = digest
|
|
51
|
+
|
|
52
|
+
signature_base = "\n".join(f"{k}: {v}" for k, v in headers.items())
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
self.verify_key.verify(signature_base.encode('utf-8'), signature_bytes)
|
|
56
|
+
return True
|
|
57
|
+
except BadSignatureError:
|
|
58
|
+
return False
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import hashlib
|
|
3
|
+
from cryptography.hazmat.backends import default_backend
|
|
4
|
+
from cryptography.hazmat.primitives.asymmetric import ed25519
|
|
5
|
+
from cryptography.hazmat.primitives import serialization
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
|
|
8
|
+
from ..__polyfill.datetime import utcnow
|
|
9
|
+
|
|
10
|
+
class OIPSigner:
|
|
11
|
+
def __init__(self, private_key):
|
|
12
|
+
self.private_key = private_key
|
|
13
|
+
|
|
14
|
+
def canonicalize(self, data: dict) -> bytes:
|
|
15
|
+
return json.dumps(data, sort_keys=True).encode('utf-8')
|
|
16
|
+
|
|
17
|
+
def hash_data(self, canonical_data) -> bytes:
|
|
18
|
+
return hashlib.sha256(canonical_data).digest()
|
|
19
|
+
|
|
20
|
+
def sign_hash(self, data_hash: bytes):
|
|
21
|
+
return self.private_key.sign(data_hash)
|
|
22
|
+
|
|
23
|
+
def sign(self, json_object: dict, publickey_url: str):
|
|
24
|
+
canonical_data = self.canonicalize(json_object)
|
|
25
|
+
data_hash: bytes = self.hash_data(canonical_data)
|
|
26
|
+
signature = self.sign_hash(data_hash)
|
|
27
|
+
proof = {
|
|
28
|
+
"@context": [
|
|
29
|
+
"https://www.w3.org/ns/activitystreams",
|
|
30
|
+
"https://w3id.org/security/data-integrity/v1"
|
|
31
|
+
],
|
|
32
|
+
"type": "DataIntegrityProof",
|
|
33
|
+
"cryptosuite": "eddsa-jcs-2022",
|
|
34
|
+
"verificationMethod": publickey_url,
|
|
35
|
+
"proofPurpose": "assertionMethod",
|
|
36
|
+
"proofValue": signature.hex(),
|
|
37
|
+
"created": utcnow().isoformat() + "Z"
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
json_object['proof'] = proof
|
|
41
|
+
return json_object
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import hashlib
|
|
3
|
+
from cryptography.hazmat.backends import default_backend
|
|
4
|
+
from cryptography.hazmat.primitives import serialization, hashes
|
|
5
|
+
from cryptography.hazmat.primitives.asymmetric import ed25519
|
|
6
|
+
|
|
7
|
+
class OIPVerifier:
|
|
8
|
+
def __init__(self, public_key):
|
|
9
|
+
self.public_key = public_key
|
|
10
|
+
|
|
11
|
+
def canonicalize(self, data: dict) -> bytes:
|
|
12
|
+
return json.dumps(data, sort_keys=True).encode('utf-8')
|
|
13
|
+
|
|
14
|
+
def hash_data(self, canonical_data: bytes) -> bytes:
|
|
15
|
+
return hashlib.sha256(canonical_data).digest()
|
|
16
|
+
|
|
17
|
+
def verify_signature(self, signature: bytes, data_hash: bytes) -> bool:
|
|
18
|
+
try:
|
|
19
|
+
self.public_key.verify(signature, data_hash)
|
|
20
|
+
return True
|
|
21
|
+
except Exception:
|
|
22
|
+
return False
|
|
23
|
+
|
|
24
|
+
def verify(self, json_object: dict) -> bool:
|
|
25
|
+
if 'proof' not in json_object:
|
|
26
|
+
raise ValueError("Proof not found in the object")
|
|
27
|
+
|
|
28
|
+
proof = json_object['proof']
|
|
29
|
+
proof_value = bytes.fromhex(proof['proofValue'])
|
|
30
|
+
|
|
31
|
+
proofless_object = json_object.copy()
|
|
32
|
+
del proofless_object['proof']
|
|
33
|
+
|
|
34
|
+
canonical_data = self.canonicalize(proofless_object)
|
|
35
|
+
data_hash = self.hash_data(canonical_data)
|
|
36
|
+
|
|
37
|
+
return self.verify_signature(proof_value, data_hash)
|
|
38
|
+
|
|
39
|
+
def load_public_key(pem_data):
|
|
40
|
+
"""PEM形式の公開鍵を読み込む"""
|
|
41
|
+
return serialization.load_pem_public_key(
|
|
42
|
+
pem_data,
|
|
43
|
+
backend=default_backend()
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
def main():
|
|
47
|
+
# 公開鍵の読み込み(例としてPEMファイルから)
|
|
48
|
+
with open("public_key.pem", "rb") as key_file:
|
|
49
|
+
public_key = load_public_key(key_file.read())
|
|
50
|
+
|
|
51
|
+
verifier = OIPVerifier(public_key)
|
|
52
|
+
|
|
53
|
+
# サンプルの署名付きJSONオブジェクト
|
|
54
|
+
signed_object = {
|
|
55
|
+
"@context": [
|
|
56
|
+
"https://www.w3.org/ns/activitystreams",
|
|
57
|
+
"https://w3id.org/security/data-integrity/v1"
|
|
58
|
+
],
|
|
59
|
+
"id": "https://server.example/objects/1",
|
|
60
|
+
"type": "Note",
|
|
61
|
+
"attributedTo": "https://server.example/users/alice",
|
|
62
|
+
"content": "Hello world",
|
|
63
|
+
"proof": {
|
|
64
|
+
"@context": [
|
|
65
|
+
"https://www.w3.org/ns/activitystreams",
|
|
66
|
+
"https://w3id.org/security/data-integrity/v1"
|
|
67
|
+
],
|
|
68
|
+
"type": "DataIntegrityProof",
|
|
69
|
+
"cryptosuite": "eddsa-jcs-2022",
|
|
70
|
+
"verificationMethod": "https://server.example/users/alice#ed25519-key",
|
|
71
|
+
"proofPurpose": "assertionMethod",
|
|
72
|
+
"proofValue": "署名の16進数文字列", # ここは実際の署名に置き換えてください
|
|
73
|
+
"created": "2023-02-24T23:36:38Z"
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
# 署名の検証
|
|
78
|
+
is_valid = verifier.verify_proof(signed_object)
|
|
79
|
+
if is_valid:
|
|
80
|
+
print("証明書は有効です。")
|
|
81
|
+
else:
|
|
82
|
+
print("証明書は無効です。")
|
|
83
|
+
|
|
84
|
+
if __name__ == "__main__":
|
|
85
|
+
main()
|
|
File without changes
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
|
|
3
|
+
from cryptography.hazmat.primitives.asymmetric import rsa
|
|
4
|
+
from cryptography.hazmat.primitives import serialization
|
|
5
|
+
from cryptography.hazmat.backends import default_backend
|
|
6
|
+
|
|
7
|
+
from http_signactures import draftSigner, draftVerifier
|
|
8
|
+
|
|
9
|
+
class TestSignatureFunctions(unittest.TestCase):
|
|
10
|
+
|
|
11
|
+
@classmethod
|
|
12
|
+
def setUpClass(cls):
|
|
13
|
+
cls.private_key = rsa.generate_private_key(
|
|
14
|
+
public_exponent=65537,
|
|
15
|
+
key_size=2048,
|
|
16
|
+
backend=default_backend()
|
|
17
|
+
)
|
|
18
|
+
cls.public_key = cls.private_key.public_key()
|
|
19
|
+
|
|
20
|
+
cls.public_pem = cls.public_key.public_bytes(
|
|
21
|
+
encoding=serialization.Encoding.PEM,
|
|
22
|
+
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
|
23
|
+
).decode('utf-8')
|
|
24
|
+
|
|
25
|
+
def test_create_and_verify_signature(self):
|
|
26
|
+
method = "POST"
|
|
27
|
+
url = "https://example.com/api/resource"
|
|
28
|
+
headers = {
|
|
29
|
+
"Content-Type": "application/json",
|
|
30
|
+
"Date": "Wed, 21 Oct 2015 07:28:00 GMT"
|
|
31
|
+
}
|
|
32
|
+
body = '{"key": "value"}'
|
|
33
|
+
|
|
34
|
+
signed_headers = draftSigner.sign(self.private_key, method, url, headers, "https://example.com/users/johndoe#main-key", body)
|
|
35
|
+
|
|
36
|
+
is_valid, message = draftVerifier.verify(self.public_pem, method, url, signed_headers, body.encode("utf-8"))
|
|
37
|
+
|
|
38
|
+
self.assertTrue(is_valid)
|
|
39
|
+
self.assertEqual(message, "Signature is valid")
|
|
40
|
+
|
|
41
|
+
def test_verify_invalid_signature(self):
|
|
42
|
+
method = "POST"
|
|
43
|
+
url = "https://example.com/api/resource"
|
|
44
|
+
headers = {
|
|
45
|
+
"Content-Type": "application/json",
|
|
46
|
+
"Date": "Wed, 21 Oct 2015 07:28:00 GMT",
|
|
47
|
+
"signature": 'keyId="your-key-id",algorithm="rsa-sha256",headers="(request-target) Content-Type Date",signature="invalid_signature"'
|
|
48
|
+
}
|
|
49
|
+
body = '{"key": "value"}'
|
|
50
|
+
|
|
51
|
+
is_valid, message = draftVerifier.verify(self.public_pem, method, url, headers, body.encode("utf-8"))
|
|
52
|
+
|
|
53
|
+
self.assertFalse(is_valid)
|
|
54
|
+
self.assertEqual(message, "Invalid signature")
|
|
55
|
+
|
|
56
|
+
def test_missing_signature_header(self):
|
|
57
|
+
method = "POST"
|
|
58
|
+
url = "https://example.com/api/resource"
|
|
59
|
+
headers = {
|
|
60
|
+
"Content-Type": "application/json",
|
|
61
|
+
"Date": "Wed, 21 Oct 2015 07:28:00 GMT"
|
|
62
|
+
}
|
|
63
|
+
body = '{"key": "value"}'
|
|
64
|
+
|
|
65
|
+
is_valid, message = draftVerifier.verify(self.public_pem, method, url, headers, body.encode("utf-8"))
|
|
66
|
+
|
|
67
|
+
self.assertFalse(is_valid)
|
|
68
|
+
self.assertEqual(message, "Signature header is missing")
|
|
69
|
+
|
|
70
|
+
if __name__ == '__main__':
|
|
71
|
+
unittest.main()
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
from http_signactures import JSONLDSigner
|
|
3
|
+
|
|
4
|
+
class TestJsonLdSigner(unittest.TestCase):
|
|
5
|
+
|
|
6
|
+
def setUp(self):
|
|
7
|
+
self.signer = JSONLDSigner()
|
|
8
|
+
self.data = {
|
|
9
|
+
"@context": [
|
|
10
|
+
"https://www.w3.org/ns/activitystreams",
|
|
11
|
+
"https://w3id.org/security/v1",
|
|
12
|
+
{
|
|
13
|
+
"Key": "sec:Key",
|
|
14
|
+
"manuallyApprovesFollowers": "as:manuallyApprovesFollowers",
|
|
15
|
+
"sensitive": "as:sensitive",
|
|
16
|
+
"Hashtag": "as:Hashtag",
|
|
17
|
+
"quoteUrl": "as:quoteUrl",
|
|
18
|
+
"toot": "http://joinmastodon.org/ns#",
|
|
19
|
+
"Emoji": "toot:Emoji",
|
|
20
|
+
"featured": "toot:featured",
|
|
21
|
+
"discoverable": "toot:discoverable",
|
|
22
|
+
"schema": "http://schema.org#",
|
|
23
|
+
"PropertyValue": "schema:PropertyValue",
|
|
24
|
+
"value": "schema:value",
|
|
25
|
+
"misskey": "https://misskey-hub.net/ns#",
|
|
26
|
+
"_misskey_content": "misskey:_misskey_content",
|
|
27
|
+
"_misskey_quote": "misskey:_misskey_quote",
|
|
28
|
+
"_misskey_reaction": "misskey:_misskey_reaction",
|
|
29
|
+
"_misskey_votes": "misskey:_misskey_votes",
|
|
30
|
+
"_misskey_summary": "misskey:_misskey_summary",
|
|
31
|
+
"isCat": "misskey:isCat",
|
|
32
|
+
"vcard": "http://www.w3.org/2006/vcard/ns#"
|
|
33
|
+
}
|
|
34
|
+
],
|
|
35
|
+
"type": "Note",
|
|
36
|
+
"content": "Hello, world!"
|
|
37
|
+
}
|
|
38
|
+
self.headers = {
|
|
39
|
+
'host': 'example.com'
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
def test_sign_and_verify(self):
|
|
43
|
+
signature_header, normalized_data = self.signer.sign(self.data, self.headers, "POST", "https://example.com/inbox", "https://example.com/users/johndoe#main-key")
|
|
44
|
+
|
|
45
|
+
is_valid = self.signer.verify(signature_header, normalized_data, self.headers)
|
|
46
|
+
self.assertTrue(is_valid)
|
|
47
|
+
|
|
48
|
+
def test_verify_invalid_signature(self):
|
|
49
|
+
signature_header, normalized_data = self.signer.sign(self.data, self.headers, "POST", "https://example.com/inbox", "https://example.com/users/johndoe#main-key")
|
|
50
|
+
|
|
51
|
+
signature_header['signature'] = 'invalid_signature'
|
|
52
|
+
|
|
53
|
+
is_valid = self.signer.verify(signature_header, normalized_data, self.headers)
|
|
54
|
+
self.assertFalse(is_valid)
|
|
55
|
+
|
|
56
|
+
if __name__ == '__main__':
|
|
57
|
+
unittest.main()
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
from cryptography.hazmat.primitives.asymmetric import ed25519
|
|
3
|
+
|
|
4
|
+
from http_signactures import OIPSigner, OIPVerifier
|
|
5
|
+
|
|
6
|
+
class TestOIPSignerVerifier(unittest.TestCase):
|
|
7
|
+
|
|
8
|
+
@classmethod
|
|
9
|
+
def setUpClass(cls):
|
|
10
|
+
cls.private_key = ed25519.Ed25519PrivateKey.generate()
|
|
11
|
+
cls.public_key = cls.private_key.public_key()
|
|
12
|
+
|
|
13
|
+
cls.publickey_url = "https://server.example/keys/test#ed25519-key"
|
|
14
|
+
|
|
15
|
+
def test_sign_and_verify(self):
|
|
16
|
+
json_object = {
|
|
17
|
+
"@context": [
|
|
18
|
+
"https://www.w3.org/ns/activitystreams",
|
|
19
|
+
"https://w3id.org/security/data-integrity/v1"
|
|
20
|
+
],
|
|
21
|
+
"id": "https://server.example/objects/1",
|
|
22
|
+
"type": "Note",
|
|
23
|
+
"attributedTo": "https://server.example/users/alice",
|
|
24
|
+
"content": "Hello world"
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
signer = OIPSigner(self.private_key)
|
|
28
|
+
signed_object = signer.sign(json_object, self.publickey_url)
|
|
29
|
+
|
|
30
|
+
verifier = OIPVerifier(self.public_key)
|
|
31
|
+
is_valid = verifier.verify(signed_object)
|
|
32
|
+
|
|
33
|
+
self.assertTrue(is_valid)
|
|
34
|
+
|
|
35
|
+
def test_verify_invalid_signature(self):
|
|
36
|
+
json_object = {
|
|
37
|
+
"@context": [
|
|
38
|
+
"https://www.w3.org/ns/activitystreams",
|
|
39
|
+
"https://w3id.org/security/data-integrity/v1"
|
|
40
|
+
],
|
|
41
|
+
"id": "https://server.example/objects/1",
|
|
42
|
+
"type": "Note",
|
|
43
|
+
"attributedTo": "https://server.example/users/alice",
|
|
44
|
+
"content": "Hello world"
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
signer = OIPSigner(self.private_key)
|
|
48
|
+
signed_object = signer.sign(json_object, self.publickey_url)
|
|
49
|
+
|
|
50
|
+
signed_object['proof']['proofValue'] = "00" # Falsified signatures
|
|
51
|
+
|
|
52
|
+
verifier = OIPVerifier(self.public_key)
|
|
53
|
+
is_valid = verifier.verify(signed_object)
|
|
54
|
+
|
|
55
|
+
self.assertFalse(is_valid)
|
|
56
|
+
|
|
57
|
+
def test_missing_proof(self):
|
|
58
|
+
json_object = {
|
|
59
|
+
"@context": [
|
|
60
|
+
"https://www.w3.org/ns/activitystreams",
|
|
61
|
+
"https://w3id.org/security/data-integrity/v1"
|
|
62
|
+
],
|
|
63
|
+
"id": "https://server.example/objects/1",
|
|
64
|
+
"type": "Note",
|
|
65
|
+
"attributedTo": "https://server.example/users/alice",
|
|
66
|
+
"content": "Hello world"
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
verifier = OIPVerifier(self.public_key)
|
|
70
|
+
|
|
71
|
+
with self.assertRaises(ValueError) as context:
|
|
72
|
+
verifier.verify(json_object)
|
|
73
|
+
|
|
74
|
+
self.assertEqual(str(context.exception), "Proof not found in the object")
|
|
75
|
+
|
|
76
|
+
if __name__ == '__main__':
|
|
77
|
+
unittest.main()
|