apsig 0.1.2__tar.gz → 0.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.
apsig-0.3.0/COPYING.md ADDED
@@ -0,0 +1,16 @@
1
+ # COPYRIGHT NOTICE
2
+ This software contains LDSignature code ported from [jointakahe/takahe](https://github.com/jointakahe/takahe). This code was originally provided under the BSD-3-Clause license, but like apsig itself is distributed under the MIT license. (This is subject to change due to requests from copyright holders, etc.)
3
+
4
+ The original code for apsig.LDSignature (from Takahe) was created by this authors:
5
+
6
+ - [Andrew Godwin](https://github.com/andrewgodwin)
7
+
8
+ Code ported (modified) by apsig from Takahe (LDSignature class)
9
+ - [/core/signatures.py](https://github.com/jointakahe/takahe/blob/d45f22c9c2f5e4feec9f9692c36b8385d51ec981/core/signatures.py#L289)
10
+
11
+ The original code is provided under the BSD-3-Clause license and is subject to the following terms and conditions
12
+
13
+ 1. redistributions of source code must retain the original copyright notice and this license notice
14
+ Use, duplication, modification, or redistribution of the source code is permitted, provided that the original copyright notice is retained.
15
+
16
+ See the [LICENSE](/LICENSE) file for the license of this entire software.
apsig-0.3.0/PKG-INFO ADDED
@@ -0,0 +1,46 @@
1
+ Metadata-Version: 2.1
2
+ Name: apsig
3
+ Version: 0.3.0
4
+ Summary: Signature implementation used in ActivityPub.
5
+ Author-Email: AmaseCocoa <amase.cocoa@gmail.com>
6
+ License: MIT
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Classifier: Topic :: Security
19
+ Classifier: Natural Language :: English
20
+ Project-URL: Source, https://github.com/AmaseCocoa/apsig
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: cryptography>=43.0.1
23
+ Requires-Dist: pynacl>=1.5.0
24
+ Requires-Dist: multiformats>=0.3.1.post4
25
+ Requires-Dist: jcs>=0.2.1
26
+ Requires-Dist: pyld[aiohttp,requests]>=2.0.4
27
+ Description-Content-Type: text/markdown
28
+
29
+ # apsig
30
+ ![PyPI](https://img.shields.io/pypi/v/apsig)
31
+ [![CodeQL](https://github.com/AmaseCocoa/apsig/actions/workflows/github-code-scanning/codeql/badge.svg?branch=main)](https://github.com/AmaseCocoa/apsig/actions/workflows/github-code-scanning/codeql)
32
+
33
+ Signature implementation used in ActivityPub.
34
+
35
+ 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)).
36
+ ## Installation
37
+ apsig is available on PyPI and can be installed with the following command.
38
+ ```
39
+ pip install apsig
40
+ ```
41
+ ## Documents
42
+ The document can be viewed [here](https://github.com/AmaseCocoa/apsig/tree/main/docs).
43
+ ## Thanks
44
+ - [Hong Minhee](https://github.com/dahlia) ([Fedify](https://fedify.dev/) Author)
45
+ - [Takahē](https://github.com/jointakahe/takahe) Authors (apsig.LDSignature was ported from Takahē)
46
+ - And All Contributor/Users
apsig-0.3.0/README.md ADDED
@@ -0,0 +1,18 @@
1
+ # apsig
2
+ ![PyPI](https://img.shields.io/pypi/v/apsig)
3
+ [![CodeQL](https://github.com/AmaseCocoa/apsig/actions/workflows/github-code-scanning/codeql/badge.svg?branch=main)](https://github.com/AmaseCocoa/apsig/actions/workflows/github-code-scanning/codeql)
4
+
5
+ Signature implementation used in ActivityPub.
6
+
7
+ 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)).
8
+ ## Installation
9
+ apsig is available on PyPI and can be installed with the following command.
10
+ ```
11
+ pip install apsig
12
+ ```
13
+ ## Documents
14
+ The document can be viewed [here](https://github.com/AmaseCocoa/apsig/tree/main/docs).
15
+ ## Thanks
16
+ - [Hong Minhee](https://github.com/dahlia) ([Fedify](https://fedify.dev/) Author)
17
+ - [Takahē](https://github.com/jointakahe/takahe) Authors (apsig.LDSignature was ported from Takahē)
18
+ - And All Contributor/Users
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "apsig"
3
- version = "0.1.2"
3
+ version = "0.3.0"
4
4
  description = "Signature implementation used in ActivityPub."
5
5
  authors = [
6
6
  { name = "AmaseCocoa", email = "amase.cocoa@gmail.com" },
@@ -8,8 +8,9 @@ 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",
11
+ "multiformats>=0.3.1.post4",
12
+ "jcs>=0.2.1",
13
+ "pyld[aiohttp,requests]>=2.0.4",
13
14
  ]
14
15
  classifiers = [
15
16
  "Development Status :: 3 - Alpha",
@@ -26,7 +27,7 @@ classifiers = [
26
27
  "Topic :: Security",
27
28
  "Natural Language :: English",
28
29
  ]
29
- requires-python = ">=3.9"
30
+ requires-python = ">=3.10"
30
31
  readme = "README.md"
31
32
 
32
33
  [project.license]
@@ -46,3 +47,10 @@ distribution = true
46
47
 
47
48
  [tool.pdm.scripts]
48
49
  test = "python test_runner.py"
50
+
51
+ [dependency-groups]
52
+ e2e = [
53
+ "aiohttp>=3.11.12",
54
+ "notturno[asgi]>=0.1.4",
55
+ "trio>=0.28.0",
56
+ ]
@@ -0,0 +1,17 @@
1
+ from .actor.keytools import KeyUtil
2
+ from .draft.sign import draftSigner
3
+ from .draft.verify import draftVerifier
4
+ from .ld_signature import LDSignature
5
+ from .proof.sign import ProofSigner
6
+ from .proof.verify import ProofVerifier
7
+
8
+ __all__ = [
9
+ "OIPSigner",
10
+ "OIPVerifier",
11
+ "ProofSigner",
12
+ "ProofVerifier",
13
+ "draftSigner",
14
+ "draftVerifier",
15
+ "LDSignature",
16
+ "KeyUtil",
17
+ ]
@@ -0,0 +1,130 @@
1
+ from typing import Self
2
+
3
+ from cryptography.hazmat.primitives.asymmetric import ed25519, rsa
4
+ from cryptography.hazmat.primitives import serialization
5
+ from cryptography.exceptions import InvalidKey
6
+
7
+ from multiformats import multibase, multicodec
8
+
9
+
10
+ class KeyUtil:
11
+ def __init__(
12
+ self: Self,
13
+ public_key: ed25519.Ed25519PublicKey | rsa.RSAPublicKey = None,
14
+ private_key: ed25519.Ed25519PrivateKey | rsa.RSAPrivateKey = None,
15
+ ):
16
+ """KeyUtil
17
+
18
+ Args:
19
+ public_key (ed25519.Ed25519PublicKey | rsa.RSAPublicKey, optional): Actor's Public Key. usually, auto generated public_key from private_key but, if private_key is none, must be set this.
20
+ private_key (ed25519.Ed25519PrivateKey | rsa.RSAPrivateKey, optional): Actor's Private Key. Defaults to None.
21
+ """
22
+ if private_key is None:
23
+ if public_key is None:
24
+ raise KeyError("If private_key is None, public_key must be set.")
25
+ else:
26
+ self.public_key = public_key
27
+ else:
28
+ self.private_key = private_key
29
+ self.public_key = private_key.public_key()
30
+
31
+ def encode_multibase(self: Self, private: bool = False) -> str:
32
+ """multibase encode the key.
33
+
34
+ Args:
35
+ private (bool, optional): If true, decodes/encodes the private key, not the public key. Defaults to False.
36
+
37
+ Returns:
38
+ str: multibase encoded string.
39
+ """
40
+ if not private:
41
+ if isinstance(self.public_key, rsa.RSAPublicKey):
42
+ prefixed = multicodec.wrap(
43
+ "rsa-pub",
44
+ self.public_key.public_bytes(
45
+ encoding=serialization.Encoding.DER,
46
+ format=serialization.PublicFormat.PKCS1,
47
+ ).hex(),
48
+ )
49
+ prefixed = multicodec.wrap(
50
+ "ed25519-pub",
51
+ self.public_key.public_bytes(
52
+ encoding=serialization.Encoding.Raw,
53
+ format=serialization.PublicFormat.Raw,
54
+ ),
55
+ )
56
+ else:
57
+ if isinstance(self.private_key, rsa.RSAPrivateKey):
58
+ prefixed = multicodec.wrap(
59
+ "rsa-priv",
60
+ self.public_key.public_bytes(
61
+ encoding=serialization.Encoding.DER,
62
+ format=serialization.PublicFormat.PKCS1,
63
+ ).hex(),
64
+ )
65
+ else:
66
+ prefixed = multicodec.wrap(
67
+ "ed25519-priv",
68
+ self.public_key.public_bytes(
69
+ encoding=serialization.Encoding.Raw,
70
+ format=serialization.PublicFormat.Raw,
71
+ ),
72
+ )
73
+ return multibase.encode(prefixed, "base58btc")
74
+
75
+ def decode_multibase(
76
+ self: Self, data: str
77
+ ) -> (
78
+ ed25519.Ed25519PublicKey
79
+ | ed25519.Ed25519PrivateKey
80
+ | rsa.RSAPublicKey
81
+ | rsa.RSAPrivateKey
82
+ ):
83
+ """Get Public/PrivateKey from Multibase.
84
+
85
+ Args:
86
+ data (str): multibase data.
87
+
88
+ Raises:
89
+ Exception: _description_
90
+ Exception: _description_
91
+ Exception: _description_
92
+ Exception: _description_
93
+ ValueError: _description_
94
+
95
+ Returns:
96
+ ed25519.Ed25519PublicKey | ed25519.Ed25519PrivateKey | rsa.RSAPublicKey | rsa.RSAPrivateKey: Loaded Key Object.
97
+ """
98
+ decoded = multibase.decode(data)
99
+ codec, data = multicodec.unwrap(decoded)
100
+ if codec.name == "ed25519-pub":
101
+ try:
102
+ return ed25519.Ed25519PublicKey.from_public_bytes(data)
103
+ except InvalidKey:
104
+ raise Exception(
105
+ "Invalid ed25519 public key passed."
106
+ ) # Tempolary, will replaced apsig's exception
107
+ elif codec.name == "rsa-pub":
108
+ try:
109
+ rsa.RSAPublicKey
110
+ return serialization.load_der_public_key(data)
111
+ except ValueError:
112
+ raise Exception(
113
+ "Invalid rsa public key passed."
114
+ ) # Tempolary, will replaced apsig's exception
115
+ if codec.name == "ed25519-priv":
116
+ try:
117
+ return ed25519.Ed25519PrivateKey.from_private_bytes(data)
118
+ except InvalidKey:
119
+ raise Exception(
120
+ "Invalid ed25519 private key passed."
121
+ ) # Tempolary, will replaced apsig's exception
122
+ elif codec.name == "rsa-priv":
123
+ try:
124
+ return serialization.load_der_private_key(data)
125
+ except ValueError:
126
+ raise Exception(
127
+ "Invalid rsa private key passed."
128
+ ) # Tempolary, will replaced apsig's exception
129
+ else:
130
+ raise ValueError("Unsupported Codec: {}".format(codec.name))
@@ -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
 
@@ -6,17 +6,33 @@ import base64
6
6
  from urllib.parse import urlparse
7
7
 
8
8
  class draftSigner:
9
- def generate_digest(body):
9
+ def _generate_digest(body: bytes | str):
10
10
  digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
11
11
  digest.update(body.encode("utf-8"))
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
+ """Signs an HTTP request with a digital signature.
17
+
18
+ Args:
19
+ private_key (rsa.RSAPrivateKey): The RSA private key used to sign the request.
20
+ method (str): The HTTP method (e.g., "GET", "POST").
21
+ url (str): The URL of the request.
22
+ headers (dict): A dictionary of HTTP headers that will be signed.
23
+ key_id (str): The key identifier to include in the signature header.
24
+ body (bytes, optional): The request body. Defaults to an empty byte string.
25
+
26
+ Returns:
27
+ dict: The HTTP headers with the signature added.
28
+
29
+ Raises:
30
+ ValueError: If the signing process fails due to invalid parameters.
31
+ """
16
32
  parsed_url = urlparse(url)
17
33
  request_target = f"(request-target): {method.lower()} {parsed_url.path}"
18
34
 
19
- digest = draftSigner.generate_digest(body)
35
+ digest = draftSigner._generate_digest(body)
20
36
  headers["digest"] = digest
21
37
 
22
38
  signature_headers = [request_target]
@@ -8,14 +8,31 @@ import datetime
8
8
  from urllib.parse import urlparse
9
9
 
10
10
  class draftVerifier:
11
- def generate_digest(body):
11
+ def _generate_digest(body: bytes | str):
12
12
  digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
13
13
  digest.update(body.encode("utf-8") if not isinstance(body, bytes) else body)
14
14
  hash_bytes = digest.finalize()
15
15
  return "SHA-256=" + base64.b64encode(hash_bytes).decode("utf-8")
16
16
 
17
17
 
18
- def verify(public_pem: str, method: str, url: str, headers: dict, body: bytes=b""):
18
+ def verify(public_pem: str, method: str, url: str, headers: dict, body: bytes=b"") -> tuple[bool, str]:
19
+ """Verifies the digital signature of an HTTP request.
20
+
21
+ Args:
22
+ public_pem (str): The public key in PEM format used to verify the signature.
23
+ method (str): The HTTP method (e.g., "GET", "POST").
24
+ url (str): The URL of the request.
25
+ headers (dict): A dictionary of HTTP headers, including the signature and other relevant information.
26
+ body (bytes, optional): The request body. Defaults to an empty byte string.
27
+
28
+ Returns:
29
+ tuple: A tuple containing:
30
+ - bool: True if the signature is valid, False otherwise.
31
+ - str: A message indicating the result of the verification.
32
+
33
+ Raises:
34
+ ValueError: If the signature header is missing or if the algorithm is unsupported.
35
+ """
19
36
  signature_header = headers.get("signature")
20
37
  if not signature_header:
21
38
  return False, "Signature header is missing"
@@ -26,7 +43,7 @@ class draftVerifier:
26
43
  signature_parts[key.strip()] = value.strip().strip('"')
27
44
 
28
45
  signature = base64.b64decode(signature_parts["signature"])
29
- keyId = signature_parts["keyId"]
46
+ #keyId = signature_parts["keyId"]
30
47
  algorithm = signature_parts["algorithm"]
31
48
 
32
49
  if algorithm != "rsa-sha256":
@@ -56,7 +73,7 @@ class draftVerifier:
56
73
  except InvalidSignature:
57
74
  return False, "Invalid signature"
58
75
 
59
- expected_digest = draftVerifier.generate_digest(body)
76
+ expected_digest = draftVerifier._generate_digest(body)
60
77
  if headers.get("digest") != expected_digest:
61
78
  return False, "Digest mismatch"
62
79
 
@@ -69,4 +86,4 @@ class draftVerifier:
69
86
  if abs((current_time - request_time).total_seconds()) > 3600:
70
87
  return False, "Date header is too far from current time"
71
88
 
72
- return True, "Signature is valid"
89
+ return True, "Signature is valid"
@@ -0,0 +1,11 @@
1
+ class SignatureError(Exception):
2
+ pass
3
+
4
+ class MissingSignature(SignatureError):
5
+ pass
6
+
7
+ class UnknownSignature(SignatureError):
8
+ pass
9
+
10
+ class VerificationFailed(SignatureError):
11
+ pass
@@ -0,0 +1,126 @@
1
+ # This code was ported from Takahe.
2
+
3
+ import datetime
4
+ import base64
5
+ from cryptography.hazmat.primitives import hashes
6
+ from cryptography.hazmat.primitives.asymmetric import rsa, padding
7
+ from cryptography.hazmat.primitives import serialization
8
+ from cryptography.hazmat.backends import default_backend
9
+
10
+ from pyld import jsonld
11
+ from cryptography.exceptions import InvalidSignature
12
+
13
+ from .__polyfill.datetime import utcnow
14
+ from multiformats import multibase, multicodec
15
+ from .exceptions import MissingSignature, UnknownSignature, VerificationFailed
16
+
17
+ class LDSignature:
18
+ """A class for signing and verifying Linked Data signatures using the RSA signature algorithm.
19
+
20
+ Attributes:
21
+ private_key (rsa.RSAPrivateKey): The RSA private key used for signing.
22
+ public_key (rsa.RSAPublicKey): The corresponding RSA public key.
23
+
24
+ Methods:
25
+ sign(doc: dict, creator: str, private_key: rsa.RSAPrivateKey, options: dict = None, created: datetime.datetime = None) -> dict:
26
+ Signs the provided document using the specified RSA private key.
27
+
28
+ verify(doc: dict, public_key: rsa.RSAPublicKey | str) -> bool:
29
+ Verifies the signature of the provided document against the given public key.
30
+ """
31
+
32
+ def __init__(self):
33
+ pass
34
+
35
+ def __normalized_hash(self, data):
36
+ norm_form = jsonld.normalize(
37
+ data, {"algorithm": "URDNA2015", "format": "application/n-quads"}
38
+ )
39
+ digest = hashes.Hash(hashes.SHA256())
40
+ digest.update(norm_form.encode("utf8"))
41
+ return digest.finalize().hex().encode("ascii")
42
+
43
+ def sign(
44
+ self,
45
+ doc: dict,
46
+ creator: str,
47
+ private_key: rsa.RSAPrivateKey,
48
+ options: dict = None,
49
+ created: datetime.datetime = None,
50
+ ):
51
+ """Signs the provided document using the specified RSA private key.
52
+
53
+ Args:
54
+ doc (dict): The document to be signed.
55
+ creator (str): The identifier of the creator of the document.
56
+ private_key (rsa.RSAPrivateKey): The RSA private key used for signing.
57
+ options (dict, optional): Additional signing options. Defaults to None.
58
+ created (datetime.datetime, optional): The timestamp when the signature is created.
59
+ Defaults to the current UTC time if not provided.
60
+
61
+ Returns:
62
+ dict: The signed document containing the original data and the signature.
63
+ """
64
+ options: dict[str, str] = {
65
+ "@context": "https://w3c-ccg.github.io/security-vocab/contexts/security-v1.jsonld", # "https://w3id.org/identity/v1"
66
+ "creator": creator,
67
+ "created": created or utcnow().strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
68
+ }
69
+
70
+ to_be_signed = self.__normalized_hash(options) + self.__normalized_hash(doc)
71
+
72
+ signature = base64.b64encode(private_key.sign(
73
+ to_be_signed, padding.PKCS1v15(), hashes.SHA256()
74
+ ))
75
+
76
+ return {
77
+ **doc,
78
+ "signature": {
79
+ **options,
80
+ "type": "RsaSignature2017",
81
+ "signatureValue": signature.decode("ascii"),
82
+ },
83
+ }
84
+
85
+ def verify(self, doc: dict, public_key: rsa.RSAPublicKey | str):
86
+ """Verifies the signature of the provided document against the given public key.
87
+
88
+ Args:
89
+ doc (dict): The signed document to verify.
90
+ public_key (rsa.RSAPublicKey | str): The RSA public key in PEM format or as a multibase-encoded string.
91
+
92
+ Returns:
93
+ bool: True if the signature is valid; otherwise, an exception is raised.
94
+
95
+ Raises:
96
+ MissingSignature: If the signature section is missing in the document.
97
+ UnknownSignature: If the signature type is not recognized.
98
+ VerificationFailed: If the signature verification fails.
99
+ """
100
+ if isinstance(public_key, str):
101
+ codec, data = multicodec.unwrap(multibase.decode(public_key))
102
+ if codec.name != "rsa-pub":
103
+ raise ValueError("public_key must be RSA PublicKey.")
104
+ public_key = serialization.load_pem_public_key(data, backend=default_backend())
105
+ try:
106
+ document = doc.copy()
107
+ signature = document.pop("signature")
108
+ options = {
109
+ "@context": "https://w3c-ccg.github.io/security-vocab/contexts/security-v1.jsonld",
110
+ "creator": signature["creator"],
111
+ "created": signature["created"],
112
+ }
113
+ except KeyError:
114
+ raise MissingSignature("Invalid signature section")
115
+ if signature["type"].lower() != "rsasignature2017":
116
+ raise UnknownSignature("Unknown signature type")
117
+ final_hash = self.__normalized_hash(options) + self.__normalized_hash(document)
118
+ try:
119
+ public_key.verify(
120
+ base64.b64decode(signature["signatureValue"]),
121
+ final_hash,
122
+ padding.PKCS1v15(),
123
+ hashes.SHA256(),
124
+ )
125
+ except InvalidSignature:
126
+ raise VerificationFailed("LDSignature mismatch")
@@ -0,0 +1,96 @@
1
+ import hashlib
2
+
3
+ import jcs
4
+ from cryptography.hazmat.primitives.asymmetric import ed25519
5
+ from multiformats import multibase, multicodec
6
+
7
+
8
+ class ProofSigner:
9
+ """
10
+ A class for signing documents using the Ed25519 signature algorithm,
11
+ implementing Object Integrity Proofs as specified in FEP-8b32.
12
+
13
+ This class provides methods to generate keys, sign data,
14
+ canonicalize documents, and create integrity proofs.
15
+
16
+ Attributes:
17
+ private_key (ed25519.Ed25519PrivateKey): The Ed25519 private key used for signing.
18
+ public_key (ed25519.Ed25519PublicKey): The corresponding Ed25519 public key.
19
+
20
+ Methods:
21
+ create_proof(unsecured_document: dict, options: dict) -> dict:
22
+ Creates a proof for the unsecured document using the specified options.
23
+
24
+ sign(unsecured_document: dict, options: dict) -> dict:
25
+ Signs the unsecured document by creating a proof and returning the signed document.
26
+ """
27
+
28
+ def __init__(self, private_key: ed25519.Ed25519PrivateKey | str):
29
+ if isinstance(private_key, str):
30
+ codec, data = multicodec.unwrap(multibase.decode(private_key))
31
+ if codec.name != "ed25519-priv":
32
+ raise TypeError("PrivateKey must be ed25519.")
33
+ else:
34
+ private_key = ed25519.Ed25519PrivateKey.from_private_bytes(data)
35
+ self.private_key, self.public_key = private_key, private_key.public_key()
36
+
37
+ def sign_data(self, hash_data):
38
+ return self.private_key.sign(hash_data)
39
+
40
+ def canonicalize(self, document):
41
+ return jcs.canonicalize(document)
42
+
43
+ def transform(self, unsecured_document, options):
44
+ if (
45
+ options["type"] != "DataIntegrityProof"
46
+ or options["cryptosuite"] != "eddsa-jcs-2022"
47
+ ):
48
+ raise ValueError("PROOF_VERIFICATION_ERROR")
49
+
50
+ canonical_document = self.canonicalize(unsecured_document)
51
+ return canonical_document
52
+
53
+ def hashing(self, transformed_document, canonical_proof_config):
54
+ transformed_document_hash = hashlib.sha256(
55
+ transformed_document.encode("utf-8") if not isinstance(transformed_document, bytes) else transformed_document
56
+ ).digest()
57
+ proof_config_hash = hashlib.sha256(
58
+ canonical_proof_config.encode("utf-8") if not isinstance(canonical_proof_config, bytes) else canonical_proof_config
59
+ ).digest()
60
+ return proof_config_hash + transformed_document_hash
61
+
62
+ def create_proof(self, unsecured_document, options):
63
+ """Creates a proof for the unsecured document using the specified options.
64
+
65
+ Args:
66
+ unsecured_document (dict): The document for which the proof is created.
67
+ options (dict): Options that define how the proof is structured.
68
+
69
+ Returns:
70
+ dict: The proof object containing the proof value and other relevant information.
71
+ """
72
+ proof = options.copy()
73
+
74
+ if "@context" in unsecured_document:
75
+ proof["@context"] = unsecured_document["@context"]
76
+
77
+ proof_config = self.canonicalize(proof)
78
+ transformed_data = self.transform(unsecured_document, options)
79
+ hash_data = self.hashing(transformed_data, proof_config)
80
+ proof_bytes = self.sign_data(hash_data)
81
+
82
+ proof["proofValue"] = multibase.encode(proof_bytes, "base58btc")
83
+ return proof
84
+
85
+ def sign(self, unsecured_document: dict, options: dict):
86
+ """Signs the unsecured document by creating a proof and returning the signed document.
87
+
88
+ Args:
89
+ unsecured_document (dict): The document to be signed.
90
+ options (dict): Options that define the signing process.
91
+
92
+ Returns:
93
+ dict: The signed document, including the proof.
94
+ """
95
+ return {**unsecured_document, "proof": self.create_proof(unsecured_document, options)}
96
+
@@ -0,0 +1,131 @@
1
+ import hashlib
2
+
3
+ import jcs
4
+ from cryptography.hazmat.primitives.asymmetric import ed25519
5
+ from multiformats import multibase, multicodec
6
+
7
+
8
+ class ProofVerifier:
9
+ """
10
+ A class for verifying documents signed using the Ed25519 signature algorithm,
11
+ implementing Object Integrity Proofs as specified in FEP-8b32.
12
+
13
+ Attributes:
14
+ public_key (ed25519.Ed25519PublicKey): The Ed25519 public key used for verification.
15
+
16
+ Methods:
17
+ verify_proof(secured_document: dict) -> dict:
18
+ Verifies the proof contained in the secured document.
19
+ verify(secured_document: dict) -> dict:
20
+ An alias for the verify_proof method.
21
+ """
22
+
23
+ def __init__(self, public_key: ed25519.Ed25519PublicKey | str):
24
+ """
25
+ Initializes the ProofVerifier with a public key.
26
+
27
+ Args:
28
+ public_key (ed25519.Ed25519PublicKey | str):
29
+ The Ed25519 public key as an object or a multibase-encoded string.
30
+
31
+ Raises:
32
+ TypeError: If the provided public key is not of type Ed25519.
33
+ """
34
+ if isinstance(public_key, str):
35
+ codec, data = multicodec.unwrap(multibase.decode(public_key))
36
+ if codec.name != "ed25519-pub":
37
+ raise TypeError("PublicKey must be ed25519.")
38
+ self.public_key: ed25519.Ed25519PublicKey = (
39
+ ed25519.Ed25519PublicKey.from_public_bytes(data)
40
+ )
41
+ else:
42
+ self.public_key: ed25519.Ed25519PublicKey = public_key
43
+
44
+ def verify_signature(self, signature, hash_data):
45
+ self.public_key.verify(signature, hash_data)
46
+
47
+ def canonicalize(self, document):
48
+ return jcs.canonicalize(document)
49
+
50
+ def transform(self, unsecured_document, options):
51
+ if (
52
+ options["type"] != "DataIntegrityProof"
53
+ or options["cryptosuite"] != "eddsa-jcs-2022"
54
+ ):
55
+ raise ValueError("PROOF_VERIFICATION_ERROR")
56
+
57
+ canonical_document = self.canonicalize(unsecured_document)
58
+ return canonical_document
59
+
60
+ def hashing(self, transformed_document, canonical_proof_config):
61
+ transformed_document_hash = hashlib.sha256(
62
+ transformed_document.encode("utf-8") if not isinstance(transformed_document, bytes) else transformed_document
63
+ ).digest()
64
+ proof_config_hash = hashlib.sha256(
65
+ canonical_proof_config.encode("utf-8") if not isinstance(canonical_proof_config, bytes) else canonical_proof_config
66
+ ).digest()
67
+ return proof_config_hash + transformed_document_hash
68
+
69
+ def verify_proof(self, secured_document: dict):
70
+ """
71
+ Verifies the proof contained in the secured document.
72
+
73
+ This method checks the integrity and authenticity of the secured document
74
+ by validating the associated proof. It verifies the signature against the
75
+ hash of the transformed document and the canonical proof configuration.
76
+
77
+ Args:
78
+ secured_document (dict): The document containing the proof to be verified.
79
+
80
+ Returns:
81
+ dict: A dictionary containing:
82
+ - bool: `verified`: Indicates whether the proof verification was successful.
83
+ - dict: `verifiedDocument`: The unsecured document if verification was successful, otherwise `None`.
84
+
85
+ Raises:
86
+ ValueError: If the proof is not found in the document.
87
+ """
88
+ if not secured_document.get("proof"):
89
+ raise ValueError("Proof not found in the object")
90
+ unsecured_document = secured_document.copy()
91
+ proof_value = unsecured_document["proof"].pop("proofValue")
92
+ proof_bytes = multibase.decode(proof_value)
93
+
94
+ proof_options = unsecured_document["proof"]
95
+
96
+ if "@context" in proof_options:
97
+ if isinstance(secured_document["@context"], str):
98
+ if not secured_document["@context"].startswith(
99
+ tuple(proof_options["@context"])
100
+ ):
101
+ return {"verified": False, "verifiedDocument": None}
102
+ elif isinstance(secured_document["@context"], list):
103
+ if not any(item.startswith(tuple(proof_options["@context"])) for item in secured_document["@context"] if isinstance(item, str)):
104
+ return {"verified": False, "verifiedDocument": None}
105
+
106
+ unsecured_document["@context"] = proof_options["@context"]
107
+
108
+ transformed_data = self.transform(unsecured_document, proof_options)
109
+ proof_config = self.canonicalize(proof_options)
110
+ hash_data = self.hashing(transformed_data, proof_config)
111
+
112
+ try:
113
+ self.verify_signature(proof_bytes, hash_data)
114
+ return {"verified": True, "verifiedDocument": unsecured_document}
115
+ except Exception:
116
+ return {"verified": False, "verifiedDocument": None}
117
+
118
+ def verify(self, secured_document: dict) -> dict:
119
+ """
120
+ An alias for the verify_proof method.
121
+
122
+ This method calls verify_proof to perform the actual verification
123
+ of the proof contained in the secured document.
124
+
125
+ Args:
126
+ secured_document (dict): The document containing the proof to be verified.
127
+
128
+ Returns:
129
+ dict: The result of the proof verification.
130
+ """
131
+ return self.verify_proof(secured_document)
@@ -0,0 +1,54 @@
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, VerificationFailed, UnknownSignature
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
+ self.ld.verify(self.signed_data, self.public_key)
30
+
31
+ def test_verify_invalid_signature_value(self):
32
+ signed_data = self.ld.sign(self.data, "https://example.com/users/johndoe#main-key", private_key=self.private_key)
33
+ signed_data["signature"]["signatureValue"] = "invalid_signature"
34
+ with self.assertRaises(VerificationFailed) as context:
35
+ self.ld.verify(signed_data, self.public_key)
36
+ self.assertEqual(str(context.exception), "LDSignature mismatch")
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
+ with self.assertRaises(UnknownSignature) as context:
50
+ self.ld.verify(signed_data, self.public_key)
51
+ self.assertEqual(str(context.exception), "Unknown signature type")
52
+
53
+ if __name__ == '__main__':
54
+ unittest.main()
@@ -0,0 +1,35 @@
1
+ import unittest
2
+
3
+ from cryptography.hazmat.primitives.asymmetric import ed25519
4
+
5
+ from apsig import KeyUtil
6
+
7
+ class TestSignatureFunctions(unittest.TestCase):
8
+
9
+ @classmethod
10
+ def setUpClass(cls):
11
+ cls.private_key = ed25519.Ed25519PrivateKey.generate()
12
+ cls.public_key = cls.private_key.public_key()
13
+ cls.public_raw = cls.public_key.public_bytes_raw()
14
+ cls.kutil = KeyUtil(private_key=cls.private_key)
15
+
16
+ def test_encode(self):
17
+ result = self.kutil.encode_multibase()
18
+ if result:
19
+ success = True
20
+ else:
21
+ success = False
22
+ self.assertTrue(success)
23
+
24
+ def test_decode(self):
25
+ multibase = self.kutil.encode_multibase()
26
+ result = self.kutil.decode_multibase(multibase)
27
+ if result:
28
+ success = True
29
+ else:
30
+ success = False
31
+
32
+ self.assertTrue(success)
33
+
34
+ if __name__ == '__main__':
35
+ unittest.main()
@@ -0,0 +1,94 @@
1
+ import unittest
2
+
3
+ from cryptography.hazmat.primitives.asymmetric import ed25519
4
+
5
+ from apsig import ProofSigner, ProofVerifier
6
+ from multiformats import multibase, multicodec
7
+
8
+
9
+ class TestProofSignerVerifier(unittest.TestCase):
10
+ @classmethod
11
+ def setUpClass(cls):
12
+ cls.private_key = ed25519.Ed25519PrivateKey.generate()
13
+ cls.public_key = cls.private_key.public_key()
14
+ cls.private_key_multibase = multibase.encode((multicodec.wrap("ed25519-priv", cls.private_key.private_bytes_raw())), base="base58btc")
15
+ cls.public_key_multibase = multibase.encode((multicodec.wrap("ed25519-pub", cls.public_key.public_bytes_raw())), base="base58btc")
16
+ cls.time = "2024-01-01T09:00:00Z"
17
+ cls.publickey_url = "https://server.example/keys/test#ed25519-key"
18
+
19
+ def test_sign_and_verify(self):
20
+ json_object = {
21
+ "@context": [
22
+ "https://www.w3.org/ns/activitystreams",
23
+ "https://w3id.org/security/data-integrity/v1",
24
+ ],
25
+ "id": "https://server.example/objects/1",
26
+ "type": "Note",
27
+ "attributedTo": "https://server.example/users/alice",
28
+ "content": "Hello world",
29
+ }
30
+
31
+ signer = ProofSigner(self.private_key)
32
+ signed_object = signer.sign(json_object, {
33
+ "type": "DataIntegrityProof",
34
+ "cryptosuite": "eddsa-jcs-2022",
35
+ "verificationMethod": "https://example.com/keys/1",
36
+ "created": self.time,
37
+ })
38
+
39
+ verifier = ProofVerifier(self.public_key)
40
+ is_valid = verifier.verify(signed_object)
41
+
42
+ self.assertTrue(is_valid)
43
+
44
+ def test_verify_invalid_signature(self):
45
+ json_object = {
46
+ "@context": [
47
+ "https://www.w3.org/ns/activitystreams",
48
+ "https://w3id.org/security/data-integrity/v1",
49
+ ],
50
+ "id": "https://server.example/objects/1",
51
+ "type": "Note",
52
+ "attributedTo": "https://server.example/users/alice",
53
+ "content": "Hello world",
54
+ }
55
+
56
+ signer = ProofSigner(self.private_key)
57
+ signed_object = signer.sign(json_object, {
58
+ "type": "DataIntegrityProof",
59
+ "cryptosuite": "eddsa-jcs-2022",
60
+ "verificationMethod": "https://example.com/keys/1",
61
+ "created": self.time,
62
+ })
63
+
64
+ signed_object["proof"]["proofValue"] = (
65
+ "zLaewdp4H9kqtwyrLatK4cjY5oRHwVcw4gibPSUDYDMhi4M49v8pcYk3ZB6D69dNpAPbUmY8ocuJ3m9KhKJEEg7z" # Dummy Text
66
+ )
67
+
68
+ verifier = ProofVerifier(self.public_key)
69
+ result = verifier.verify(signed_object)
70
+
71
+ self.assertFalse(result["verified"])
72
+
73
+ def test_missing_proof(self):
74
+ json_object = {
75
+ "@context": [
76
+ "https://www.w3.org/ns/activitystreams",
77
+ "https://w3id.org/security/data-integrity/v1",
78
+ ],
79
+ "id": "https://server.example/objects/1",
80
+ "type": "Note",
81
+ "attributedTo": "https://server.example/users/alice",
82
+ "content": "Hello world",
83
+ }
84
+
85
+ verifier = ProofVerifier(self.public_key)
86
+
87
+ with self.assertRaises(ValueError) as context:
88
+ verifier.verify(json_object)
89
+
90
+ self.assertEqual(str(context.exception), "Proof not found in the object")
91
+
92
+
93
+ if __name__ == "__main__":
94
+ unittest.main()
apsig-0.1.2/PKG-INFO DELETED
@@ -1,31 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: apsig
3
- Version: 0.1.2
4
- Summary: Signature implementation used in ActivityPub.
5
- Author-Email: AmaseCocoa <amase.cocoa@gmail.com>
6
- License: MIT
7
- Classifier: Development Status :: 3 - Alpha
8
- Classifier: Intended Audience :: Developers
9
- Classifier: License :: OSI Approved :: MIT License
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: Programming Language :: Python :: 3.9
12
- Classifier: Programming Language :: Python :: 3.10
13
- Classifier: Programming Language :: Python :: 3.11
14
- Classifier: Programming Language :: Python :: 3.12
15
- Classifier: Programming Language :: Python :: 3.13
16
- Classifier: Operating System :: OS Independent
17
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
- Classifier: Topic :: Security
19
- Classifier: Natural Language :: English
20
- Project-URL: Source, https://github.com/AmaseCocoa/apsig
21
- Requires-Python: >=3.9
22
- Requires-Dist: cryptography>=43.0.1
23
- Requires-Dist: pynacl>=1.5.0
24
- Requires-Dist: pyld>=2.0.4
25
- Requires-Dist: aiohttp>=3.10.5
26
- Description-Content-Type: text/markdown
27
-
28
- # apsig
29
- Signature implementation used in ActivityPub.
30
-
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).
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,7 +0,0 @@
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"]
@@ -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,41 +0,0 @@
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
@@ -1,85 +0,0 @@
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()
@@ -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()
@@ -1,77 +0,0 @@
1
- import unittest
2
- from cryptography.hazmat.primitives.asymmetric import ed25519
3
-
4
- from apsig 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()
File without changes
File without changes
File without changes