apsig 0.1.2__tar.gz → 0.2.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: apsig
3
- Version: 0.1.2
3
+ Version: 0.2.0
4
4
  Summary: Signature implementation used in ActivityPub.
5
5
  Author-Email: AmaseCocoa <amase.cocoa@gmail.com>
6
6
  License: MIT
@@ -21,11 +21,14 @@ Project-URL: Source, https://github.com/AmaseCocoa/apsig
21
21
  Requires-Python: >=3.9
22
22
  Requires-Dist: cryptography>=43.0.1
23
23
  Requires-Dist: pynacl>=1.5.0
24
- Requires-Dist: pyld>=2.0.4
25
- Requires-Dist: aiohttp>=3.10.5
26
24
  Description-Content-Type: text/markdown
27
25
 
28
26
  # apsig
29
27
  Signature implementation used in ActivityPub.
30
28
 
31
- 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).
29
+ This library implements the creation/verification of signatures for HTTP Signatures ([draft-cavage-http-signatures-12](https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-12)), [Linked Data Signatures](https://docs.joinmastodon.org/spec/security/#ld), and Object Integrity Proofs ([FEP-8b32](https://codeberg.org/fediverse/fep/src/branch/main/fep/8b32/fep-8b32.md)).
30
+ ## Installation
31
+ apsig is available on PyPI and can be installed with the following command.
32
+ ```
33
+ pip install apsig
34
+ ```
apsig-0.2.0/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # apsig
2
+ Signature implementation used in ActivityPub.
3
+
4
+ This library implements the creation/verification of signatures for HTTP Signatures ([draft-cavage-http-signatures-12](https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-12)), [Linked Data Signatures](https://docs.joinmastodon.org/spec/security/#ld), and Object Integrity Proofs ([FEP-8b32](https://codeberg.org/fediverse/fep/src/branch/main/fep/8b32/fep-8b32.md)).
5
+ ## Installation
6
+ apsig is available on PyPI and can be installed with the following command.
7
+ ```
8
+ pip install apsig
9
+ ```
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "apsig"
3
- version = "0.1.2"
3
+ version = "0.2.0"
4
4
  description = "Signature implementation used in ActivityPub."
5
5
  authors = [
6
6
  { name = "AmaseCocoa", email = "amase.cocoa@gmail.com" },
@@ -8,8 +8,6 @@ authors = [
8
8
  dependencies = [
9
9
  "cryptography>=43.0.1",
10
10
  "pynacl>=1.5.0",
11
- "pyld>=2.0.4",
12
- "aiohttp>=3.10.5",
13
11
  ]
14
12
  classifiers = [
15
13
  "Development Status :: 3 - Alpha",
@@ -2,6 +2,6 @@ from .object_integrity_proofs.sign import OIPSigner
2
2
  from .object_integrity_proofs.verify import OIPVerifier
3
3
  from .draft.sign import draftSigner
4
4
  from .draft.verify import draftVerifier
5
- from .ld.ldsig import JSONLDSigner
5
+ from .ld_signature import LDSignature
6
6
 
7
- __all__ = ["OIPSigner", "OIPVerifier" , "draftSigner", "draftVerifier", "JSONLDSigner"]
7
+ __all__ = ["OIPSigner", "OIPVerifier" , "draftSigner", "draftVerifier", "LDSignature"]
@@ -1,4 +1,4 @@
1
- from cryptography.hazmat.primitives.asymmetric import padding
1
+ from cryptography.hazmat.primitives.asymmetric import padding, rsa
2
2
  from cryptography.hazmat.primitives import hashes
3
3
  from cryptography.hazmat.backends import default_backend
4
4
 
@@ -12,7 +12,7 @@ class draftSigner:
12
12
  hash_bytes = digest.finalize()
13
13
  return "SHA-256=" + base64.b64encode(hash_bytes).decode("utf-8")
14
14
 
15
- def sign(private_key, method: str, url: str, headers: dict, key_id: str, body: bytes="") -> dict:
15
+ def sign(private_key: rsa.RSAPrivateKey, method: str, url: str, headers: dict, key_id: str, body: bytes="") -> dict:
16
16
  parsed_url = urlparse(url)
17
17
  request_target = f"(request-target): {method.lower()} {parsed_url.path}"
18
18
 
@@ -26,7 +26,7 @@ class draftVerifier:
26
26
  signature_parts[key.strip()] = value.strip().strip('"')
27
27
 
28
28
  signature = base64.b64decode(signature_parts["signature"])
29
- keyId = signature_parts["keyId"]
29
+ #keyId = signature_parts["keyId"]
30
30
  algorithm = signature_parts["algorithm"]
31
31
 
32
32
  if algorithm != "rsa-sha256":
@@ -69,4 +69,4 @@ class draftVerifier:
69
69
  if abs((current_time - request_time).total_seconds()) > 3600:
70
70
  return False, "Date header is too far from current time"
71
71
 
72
- return True, "Signature is valid"
72
+ return True, "Signature is valid"
@@ -0,0 +1,2 @@
1
+ class MissingSignature(Exception):
2
+ pass
@@ -0,0 +1,84 @@
1
+ import hashlib
2
+ import os
3
+ import json
4
+ from cryptography.hazmat.backends import default_backend
5
+ from cryptography.hazmat.primitives import hashes
6
+ from cryptography.hazmat.primitives.asymmetric import padding, rsa
7
+
8
+ from .__polyfill.datetime import utcnow
9
+ from .exceptions import MissingSignature
10
+
11
+ class LDSignature:
12
+ def __init__(self):
13
+ pass
14
+
15
+ def __normalize(self, data):
16
+ if isinstance(data, dict):
17
+ normalized = {k: self.__normalize(v) for k, v in sorted(data.items())}
18
+ elif isinstance(data, list):
19
+ normalized = [self.__normalize(item) for item in sorted(data)]
20
+ else:
21
+ normalized = data
22
+ return normalized
23
+
24
+ def __create_verify_data(self, data, options):
25
+ transformed_options = {**options}
26
+ transformed_options.pop("type", None)
27
+ transformed_options.pop("id", None)
28
+ transformed_options.pop("signatureValue", None)
29
+
30
+ normalized_options = self.__normalize(transformed_options)
31
+ options_hash = hashlib.sha256(json.dumps(normalized_options, sort_keys=True).encode("utf-8")).hexdigest()
32
+
33
+ transformed_data = {**data}
34
+ transformed_data.pop("signature", None)
35
+
36
+ normalized_data = self.__normalize(transformed_data)
37
+ document_hash = hashlib.sha256(json.dumps(normalized_data, sort_keys=True).encode("utf-8")).hexdigest()
38
+
39
+ verify_data = f"{options_hash}{document_hash}"
40
+ return verify_data
41
+
42
+ def sign(self, data, creator, domain=None, created=None, private_key=None):
43
+ options = {
44
+ "type": "RsaSignature2017",
45
+ "creator": creator,
46
+ "domain": domain,
47
+ "nonce": os.urandom(16).hex(),
48
+ "created": created or utcnow().isoformat(),
49
+ }
50
+ if not domain:
51
+ options.pop("domain", None)
52
+
53
+ to_be_signed = self.__create_verify_data(data, options)
54
+
55
+ signer = private_key.sign(
56
+ to_be_signed.encode("utf-8"), padding.PKCS1v15(), hashes.SHA256()
57
+ )
58
+
59
+ return {**data, "signature": {**options, "signatureValue": signer.hex()}}
60
+
61
+ def verify(self, data, public_key):
62
+ if data.get("signature") is None:
63
+ raise MissingSignature
64
+ to_be_signed = self.__create_verify_data(data, data["signature"])
65
+
66
+
67
+ try:
68
+ public_key.verify(
69
+ bytes.fromhex(data["signature"]["signatureValue"]),
70
+ to_be_signed.encode("utf-8"),
71
+ padding.PKCS1v15(),
72
+ hashes.SHA256(),
73
+ )
74
+ return True
75
+ except Exception:
76
+ return False
77
+
78
+ @staticmethod
79
+ def generate_rsa_keypair():
80
+ private_key = rsa.generate_private_key(
81
+ public_exponent=65537, key_size=2048, backend=default_backend()
82
+ )
83
+ public_key = private_key.public_key()
84
+ return private_key, public_key
@@ -1,9 +1,5 @@
1
1
  import json
2
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
3
 
8
4
  from ..__polyfill.datetime import utcnow
9
5
 
@@ -38,4 +34,4 @@ class OIPSigner:
38
34
  }
39
35
 
40
36
  json_object['proof'] = proof
41
- return json_object
37
+ return json_object
@@ -1,8 +1,7 @@
1
1
  import json
2
2
  import hashlib
3
3
  from cryptography.hazmat.backends import default_backend
4
- from cryptography.hazmat.primitives import serialization, hashes
5
- from cryptography.hazmat.primitives.asymmetric import ed25519
4
+ from cryptography.hazmat.primitives import serialization
6
5
 
7
6
  class OIPVerifier:
8
7
  def __init__(self, public_key):
@@ -0,0 +1,53 @@
1
+ import unittest
2
+
3
+ from apsig import LDSignature
4
+ from cryptography.hazmat.backends import default_backend
5
+ from cryptography.hazmat.primitives.asymmetric import rsa
6
+
7
+ from apsig.exceptions import MissingSignature
8
+
9
+ class TestJsonLdSigner(unittest.TestCase):
10
+ def setUp(self):
11
+ self.private_key = rsa.generate_private_key(
12
+ public_exponent=65537,
13
+ key_size=2048,
14
+ backend=default_backend()
15
+ )
16
+ self.public_key = self.private_key.public_key()
17
+ self.ld = LDSignature()
18
+ self.data = {
19
+ "@context": [
20
+ "https://www.w3.org/ns/activitystreams",
21
+ "https://w3id.org/security/v1",
22
+ ],
23
+ "type": "Note",
24
+ "content": "Hello, world!"
25
+ }
26
+ self.signed_data = self.ld.sign(self.data, "https://example.com/users/johndoe#main-key", private_key=self.private_key)
27
+
28
+ def test_sign_and_verify(self):
29
+ is_valid = self.ld.verify(self.signed_data, self.public_key)
30
+ self.assertTrue(is_valid)
31
+
32
+ def test_verify_invalid_signature_value(self):
33
+ signed_data = self.ld.sign(self.data, "https://example.com/users/johndoe#main-key", private_key=self.private_key)
34
+ signed_data["signature"]["signatureValue"] = "invalid_signature"
35
+ is_valid = self.ld.verify(signed_data, self.public_key)
36
+ self.assertFalse(is_valid)
37
+
38
+ def test_verify_missing_signature(self):
39
+ try:
40
+ self.ld.verify(self.data, self.public_key)
41
+ is_fail = False
42
+ except MissingSignature:
43
+ is_fail = True
44
+ self.assertTrue(is_fail)
45
+
46
+ def test_verify_invalid_signature(self):
47
+ signed_data = self.ld.sign(self.data, "https://example.com/users/johndoe#main-key", private_key=self.private_key)
48
+ signed_data["signature"]["type"] = "RsaSignatureHoge"
49
+ is_fail = self.ld.verify(signed_data, self.public_key)
50
+ self.assertTrue(is_fail)
51
+
52
+ if __name__ == '__main__':
53
+ unittest.main()
apsig-0.1.2/README.md DELETED
@@ -1,4 +0,0 @@
1
- # apsig
2
- Signature implementation used in ActivityPub.
3
-
4
- 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).
@@ -1,58 +0,0 @@
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
@@ -1,57 +0,0 @@
1
- import unittest
2
- from apsig 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()
File without changes
File without changes
File without changes
File without changes