We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
SecureSerializer fails on certain types and binary serializers
<!--
Please fill this template entirely and do not erase parts of it.
We reserve the right to close without a response
bug reports which are incomplete.
-->
# Checklist
<!--
To check an item on the list replace [ ] with [x].
-->
- [X] I have verified that the issue exists against the `main` branch of Celery.
- [ ] This has already been asked to the [discussions forum](https://github.com/celery/celery/discussions) first.
- [X] I have read the relevant section in the
  [contribution guide](https://docs.celeryq.dev/en/main/contributing.html#other-bugs)
  on reporting bugs.
- [X] I have checked the [issues list](https://github.com/celery/celery/issues?q=is%3Aissue+label%3A%22Issue+Type%3A+Bug+Report%22+-label%3A%22Category%3A+Documentation%22)
  for similar or identical bug reports.
- [X] I have checked the [pull requests list](https://github.com/celery/celery/pulls?q=is%3Apr+label%3A%22PR+Type%3A+Bugfix%22+-label%3A%22Category%3A+Documentation%22)
  for existing proposed fixes.
- [X] I have checked the [commit log](https://github.com/celery/celery/commits/main)
  to find out if the bug was already fixed in the main branch.
- [X] I have included all related issues and possible duplicate issues
  in this issue (If there are none, check this box anyway).
- [X] I have tried to reproduce the issue with [pytest-celery](https://docs.celeryq.dev/projects/pytest-celery/en/latest/userguide/celery-bug-report.html) and added the reproduction script below.

## Mandatory Debugging Information

- [ ] I have included the output of ``celery -A proj report`` in the issue.
    (if you are not able to do this, then at least specify the Celery
     version affected).
- [X] I have verified that the issue exists against the `main` branch of Celery.
- [ ] I have included the contents of ``pip freeze`` in the issue.
- [ ] I have included all the versions of all the external dependencies required
  to reproduce this bug.

## Optional Debugging Information
<!--
Try some of the below if you think they are relevant.
It will help us figure out the scope of the bug and how many users it affects.
-->
- [ ] I have tried reproducing the issue on more than one Python version
  and/or implementation.
- [ ] I have tried reproducing the issue on more than one message broker and/or
  result backend.
- [ ] I have tried reproducing the issue on more than one version of the message
  broker and/or result backend.
- [ ] I have tried reproducing the issue on more than one operating system.
- [ ] I have tried reproducing the issue on more than one workers pool.
- [ ] I have tried reproducing the issue with autoscaling, retries,
  ETA/Countdown & rate limits disabled.
- [ ] I have tried reproducing the issue after downgrading
  and/or upgrading Celery and its dependencies.

## Related Issues and Possible Duplicates
<!--
Please make sure to search and mention any related issues
or possible duplicates to this issue as requested by the checklist above.

This may or may not include issues in other repositories that the Celery project
maintains or other repositories that are dependencies of Celery.

If you don't know how to mention issues, please refer to Github's documentation
on the subject: https://help.github.com/en/articles/autolinked-references-and-urls#issues-and-pull-requests
-->

#### Related Issues

- None

#### Possible Duplicates

- None

## Environment & Settings
<!-- Include the contents of celery --version below -->
**Celery version**:
<!-- Include the output of celery -A proj report below -->
<details>
<summary><b><code>celery report</code> Output:</b></summary>
<p>

```
```

</p>
</details>

# Steps to Reproduce

## Required Dependencies
<!-- Please fill the required dependencies to reproduce this issue -->
- **Minimal Python Version**: N/A or Unknown
- **Minimal Celery Version**: N/A or Unknown
- **Minimal Kombu Version**: N/A or Unknown
- **Minimal Broker Version**: N/A or Unknown
- **Minimal Result Backend Version**: N/A or Unknown
- **Minimal OS and/or Kernel Version**: N/A or Unknown
- **Minimal Broker Client Version**: N/A or Unknown
- **Minimal Result Backend Client Version**: N/A or Unknown

### Python Packages
<!-- Please fill the contents of pip freeze below -->
<details>
<summary><b><code>pip freeze</code> Output:</b></summary>
<p>

```
```

</p>
</details>

### Other Dependencies
<!--
Please provide system dependencies, configuration files
and other dependency information if applicable
-->
<details>
<p>
N/A
</p>
</details>

## Minimally Reproducible Test Case
<!--
Please provide a reproducible test case.
Refer to the Reporting Bugs section in our contribution guide.

We prefer submitting test cases in the form of a PR to our integration test suite.
If you can provide one, please mention the PR number below.
If not, please attach the most minimal code example required to reproduce the issue below.
If the test case is too large, please include a link to a gist or a repository below.

Alternatively, the pytest-celery plugin can be used to create standalone reproduction scripts
that can be added to this report. See the pytest-celery documentation for more information at
pytest-celery.readthedocs.io
-->

<details>
<p>

```python

app.conf.update(
    security_key='/private/keys/celery/private.key',
    security_certificate='/private/keys/celery/public.pem',
    security_cert_store='/private/keys/celery/*.pem')

app.setup_security()

@app.task
def serializer_test_task(arg: Any) -> Any:
    return arg

def test_serialize(data):
    res = serializer_test_task.delay(data)
    deserialized_value = res.get()
    assert deserialized_value == data

test_serialize(data=b"foo") # fails to validate signature

#############

app.setup_security(serializer="pickle")
test_serialize(data="foo") # fails to serialize any value using pickle serializer

```

</p>
</details>

# Expected Behavior


# Actual Behavior

There are several bugs in the SecureSerializer feature:
 - When using the 'json' serializer (default), it will always fail to validate the signature if the passed value is of type 'bytes'
- When using the other binary serializer (and not a string-based serializer like 'json'), for example 'pickle', the serializer is completely broken. 


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `celery/security/serialization.py`
Content:
```
1 """Secure serializer."""
2 from kombu.serialization import dumps, loads, registry
3 from kombu.utils.encoding import bytes_to_str, ensure_bytes, str_to_bytes
4 
5 from celery.app.defaults import DEFAULT_SECURITY_DIGEST
6 from celery.utils.serialization import b64decode, b64encode
7 
8 from .certificate import Certificate, FSCertStore
9 from .key import PrivateKey
10 from .utils import get_digest_algorithm, reraise_errors
11 
12 __all__ = ('SecureSerializer', 'register_auth')
13 
14 
15 class SecureSerializer:
16     """Signed serializer."""
17 
18     def __init__(self, key=None, cert=None, cert_store=None,
19                  digest=DEFAULT_SECURITY_DIGEST, serializer='json'):
20         self._key = key
21         self._cert = cert
22         self._cert_store = cert_store
23         self._digest = get_digest_algorithm(digest)
24         self._serializer = serializer
25 
26     def serialize(self, data):
27         """Serialize data structure into string."""
28         assert self._key is not None
29         assert self._cert is not None
30         with reraise_errors('Unable to serialize: {0!r}', (Exception,)):
31             content_type, content_encoding, body = dumps(
32                 bytes_to_str(data), serializer=self._serializer)
33             # What we sign is the serialized body, not the body itself.
34             # this way the receiver doesn't have to decode the contents
35             # to verify the signature (and thus avoiding potential flaws
36             # in the decoding step).
37             body = ensure_bytes(body)
38             return self._pack(body, content_type, content_encoding,
39                               signature=self._key.sign(body, self._digest),
40                               signer=self._cert.get_id())
41 
42     def deserialize(self, data):
43         """Deserialize data structure from string."""
44         assert self._cert_store is not None
45         with reraise_errors('Unable to deserialize: {0!r}', (Exception,)):
46             payload = self._unpack(data)
47             signature, signer, body = (payload['signature'],
48                                        payload['signer'],
49                                        payload['body'])
50             self._cert_store[signer].verify(body, signature, self._digest)
51         return loads(bytes_to_str(body), payload['content_type'],
52                      payload['content_encoding'], force=True)
53 
54     def _pack(self, body, content_type, content_encoding, signer, signature,
55               sep=str_to_bytes('\x00\x01')):
56         fields = sep.join(
57             ensure_bytes(s) for s in [signer, signature, content_type,
58                                       content_encoding, body]
59         )
60         return b64encode(fields)
61 
62     def _unpack(self, payload, sep=str_to_bytes('\x00\x01')):
63         raw_payload = b64decode(ensure_bytes(payload))
64         first_sep = raw_payload.find(sep)
65 
66         signer = raw_payload[:first_sep]
67         signer_cert = self._cert_store[signer]
68 
69         # shift 3 bits right to get signature length
70         # 2048bit rsa key has a signature length of 256
71         # 4096bit rsa key has a signature length of 512
72         sig_len = signer_cert.get_pubkey().key_size >> 3
73         sep_len = len(sep)
74         signature_start_position = first_sep + sep_len
75         signature_end_position = signature_start_position + sig_len
76         signature = raw_payload[
77             signature_start_position:signature_end_position
78         ]
79 
80         v = raw_payload[signature_end_position + sep_len:].split(sep)
81 
82         return {
83             'signer': signer,
84             'signature': signature,
85             'content_type': bytes_to_str(v[0]),
86             'content_encoding': bytes_to_str(v[1]),
87             'body': bytes_to_str(v[2]),
88         }
89 
90 
91 def register_auth(key=None, key_password=None, cert=None, store=None,
92                   digest=DEFAULT_SECURITY_DIGEST,
93                   serializer='json'):
94     """Register security serializer."""
95     s = SecureSerializer(key and PrivateKey(key, password=key_password),
96                          cert and Certificate(cert),
97                          store and FSCertStore(store),
98                          digest, serializer=serializer)
99     registry.register('auth', s.serialize, s.deserialize,
100                       content_type='application/data',
101                       content_encoding='utf-8')
102
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/celery/security/serialization.py b/celery/security/serialization.py
--- a/celery/security/serialization.py
+++ b/celery/security/serialization.py
@@ -29,7 +29,8 @@
         assert self._cert is not None
         with reraise_errors('Unable to serialize: {0!r}', (Exception,)):
             content_type, content_encoding, body = dumps(
-                bytes_to_str(data), serializer=self._serializer)
+                data, serializer=self._serializer)
+
             # What we sign is the serialized body, not the body itself.
             # this way the receiver doesn't have to decode the contents
             # to verify the signature (and thus avoiding potential flaws
@@ -48,7 +49,7 @@
                                        payload['signer'],
                                        payload['body'])
             self._cert_store[signer].verify(body, signature, self._digest)
-        return loads(bytes_to_str(body), payload['content_type'],
+        return loads(body, payload['content_type'],
                      payload['content_encoding'], force=True)
 
     def _pack(self, body, content_type, content_encoding, signer, signature,
@@ -84,7 +85,7 @@
             'signature': signature,
             'content_type': bytes_to_str(v[0]),
             'content_encoding': bytes_to_str(v[1]),
-            'body': bytes_to_str(v[2]),
+            'body': v[2],
         }

{"golden_diff": "diff --git a/celery/security/serialization.py b/celery/security/serialization.py\n--- a/celery/security/serialization.py\n+++ b/celery/security/serialization.py\n@@ -29,7 +29,8 @@\n         assert self._cert is not None\n         with reraise_errors('Unable to serialize: {0!r}', (Exception,)):\n             content_type, content_encoding, body = dumps(\n-                bytes_to_str(data), serializer=self._serializer)\n+                data, serializer=self._serializer)\n+\n             # What we sign is the serialized body, not the body itself.\n             # this way the receiver doesn't have to decode the contents\n             # to verify the signature (and thus avoiding potential flaws\n@@ -48,7 +49,7 @@\n                                        payload['signer'],\n                                        payload['body'])\n             self._cert_store[signer].verify(body, signature, self._digest)\n-        return loads(bytes_to_str(body), payload['content_type'],\n+        return loads(body, payload['content_type'],\n                      payload['content_encoding'], force=True)\n \n     def _pack(self, body, content_type, content_encoding, signer, signature,\n@@ -84,7 +85,7 @@\n             'signature': signature,\n             'content_type': bytes_to_str(v[0]),\n             'content_encoding': bytes_to_str(v[1]),\n-            'body': bytes_to_str(v[2]),\n+            'body': v[2],\n         }\n", "issue": "SecureSerializer fails on certain types and binary serializers\n<!--\r\nPlease fill this template entirely and do not erase parts of it.\r\nWe reserve the right to close without a response\r\nbug reports which are incomplete.\r\n-->\r\n# Checklist\r\n<!--\r\nTo check an item on the list replace [ ] with [x].\r\n-->\r\n- [X] I have verified that the issue exists against the `main` branch of Celery.\r\n- [ ] This has already been asked to the [discussions forum](https://github.com/celery/celery/discussions) first.\r\n- [X] I have read the relevant section in the\r\n  [contribution guide](https://docs.celeryq.dev/en/main/contributing.html#other-bugs)\r\n  on reporting bugs.\r\n- [X] I have checked the [issues list](https://github.com/celery/celery/issues?q=is%3Aissue+label%3A%22Issue+Type%3A+Bug+Report%22+-label%3A%22Category%3A+Documentation%22)\r\n  for similar or identical bug reports.\r\n- [X] I have checked the [pull requests list](https://github.com/celery/celery/pulls?q=is%3Apr+label%3A%22PR+Type%3A+Bugfix%22+-label%3A%22Category%3A+Documentation%22)\r\n  for existing proposed fixes.\r\n- [X] I have checked the [commit log](https://github.com/celery/celery/commits/main)\r\n  to find out if the bug was already fixed in the main branch.\r\n- [X] I have included all related issues and possible duplicate issues\r\n  in this issue (If there are none, check this box anyway).\r\n- [X] I have tried to reproduce the issue with [pytest-celery](https://docs.celeryq.dev/projects/pytest-celery/en/latest/userguide/celery-bug-report.html) and added the reproduction script below.\r\n\r\n## Mandatory Debugging Information\r\n\r\n- [ ] I have included the output of ``celery -A proj report`` in the issue.\r\n    (if you are not able to do this, then at least specify the Celery\r\n     version affected).\r\n- [X] I have verified that the issue exists against the `main` branch of Celery.\r\n- [ ] I have included the contents of ``pip freeze`` in the issue.\r\n- [ ] I have included all the versions of all the external dependencies required\r\n  to reproduce this bug.\r\n\r\n## Optional Debugging Information\r\n<!--\r\nTry some of the below if you think they are relevant.\r\nIt will help us figure out the scope of the bug and how many users it affects.\r\n-->\r\n- [ ] I have tried reproducing the issue on more than one Python version\r\n  and/or implementation.\r\n- [ ] I have tried reproducing the issue on more than one message broker and/or\r\n  result backend.\r\n- [ ] I have tried reproducing the issue on more than one version of the message\r\n  broker and/or result backend.\r\n- [ ] I have tried reproducing the issue on more than one operating system.\r\n- [ ] I have tried reproducing the issue on more than one workers pool.\r\n- [ ] I have tried reproducing the issue with autoscaling, retries,\r\n  ETA/Countdown & rate limits disabled.\r\n- [ ] I have tried reproducing the issue after downgrading\r\n  and/or upgrading Celery and its dependencies.\r\n\r\n## Related Issues and Possible Duplicates\r\n<!--\r\nPlease make sure to search and mention any related issues\r\nor possible duplicates to this issue as requested by the checklist above.\r\n\r\nThis may or may not include issues in other repositories that the Celery project\r\nmaintains or other repositories that are dependencies of Celery.\r\n\r\nIf you don't know how to mention issues, please refer to Github's documentation\r\non the subject: https://help.github.com/en/articles/autolinked-references-and-urls#issues-and-pull-requests\r\n-->\r\n\r\n#### Related Issues\r\n\r\n- None\r\n\r\n#### Possible Duplicates\r\n\r\n- None\r\n\r\n## Environment & Settings\r\n<!-- Include the contents of celery --version below -->\r\n**Celery version**:\r\n<!-- Include the output of celery -A proj report below -->\r\n<details>\r\n<summary><b><code>celery report</code> Output:</b></summary>\r\n<p>\r\n\r\n```\r\n```\r\n\r\n</p>\r\n</details>\r\n\r\n# Steps to Reproduce\r\n\r\n## Required Dependencies\r\n<!-- Please fill the required dependencies to reproduce this issue -->\r\n- **Minimal Python Version**: N/A or Unknown\r\n- **Minimal Celery Version**: N/A or Unknown\r\n- **Minimal Kombu Version**: N/A or Unknown\r\n- **Minimal Broker Version**: N/A or Unknown\r\n- **Minimal Result Backend Version**: N/A or Unknown\r\n- **Minimal OS and/or Kernel Version**: N/A or Unknown\r\n- **Minimal Broker Client Version**: N/A or Unknown\r\n- **Minimal Result Backend Client Version**: N/A or Unknown\r\n\r\n### Python Packages\r\n<!-- Please fill the contents of pip freeze below -->\r\n<details>\r\n<summary><b><code>pip freeze</code> Output:</b></summary>\r\n<p>\r\n\r\n```\r\n```\r\n\r\n</p>\r\n</details>\r\n\r\n### Other Dependencies\r\n<!--\r\nPlease provide system dependencies, configuration files\r\nand other dependency information if applicable\r\n-->\r\n<details>\r\n<p>\r\nN/A\r\n</p>\r\n</details>\r\n\r\n## Minimally Reproducible Test Case\r\n<!--\r\nPlease provide a reproducible test case.\r\nRefer to the Reporting Bugs section in our contribution guide.\r\n\r\nWe prefer submitting test cases in the form of a PR to our integration test suite.\r\nIf you can provide one, please mention the PR number below.\r\nIf not, please attach the most minimal code example required to reproduce the issue below.\r\nIf the test case is too large, please include a link to a gist or a repository below.\r\n\r\nAlternatively, the pytest-celery plugin can be used to create standalone reproduction scripts\r\nthat can be added to this report. See the pytest-celery documentation for more information at\r\npytest-celery.readthedocs.io\r\n-->\r\n\r\n<details>\r\n<p>\r\n\r\n```python\r\n\r\napp.conf.update(\r\n    security_key='/private/keys/celery/private.key',\r\n    security_certificate='/private/keys/celery/public.pem',\r\n    security_cert_store='/private/keys/celery/*.pem')\r\n\r\napp.setup_security()\r\n\r\n@app.task\r\ndef serializer_test_task(arg: Any) -> Any:\r\n    return arg\r\n\r\ndef test_serialize(data):\r\n    res = serializer_test_task.delay(data)\r\n    deserialized_value = res.get()\r\n    assert deserialized_value == data\r\n\r\ntest_serialize(data=b\"foo\") # fails to validate signature\r\n\r\n#############\r\n\r\napp.setup_security(serializer=\"pickle\")\r\ntest_serialize(data=\"foo\") # fails to serialize any value using pickle serializer\r\n\r\n```\r\n\r\n</p>\r\n</details>\r\n\r\n# Expected Behavior\r\n\r\n\r\n# Actual Behavior\r\n\r\nThere are several bugs in the SecureSerializer feature:\r\n - When using the 'json' serializer (default), it will always fail to validate the signature if the passed value is of type 'bytes'\r\n- When using the other binary serializer (and not a string-based serializer like 'json'), for example 'pickle', the serializer is completely broken. \r\n\n", "before_files": [{"content": "\"\"\"Secure serializer.\"\"\"\nfrom kombu.serialization import dumps, loads, registry\nfrom kombu.utils.encoding import bytes_to_str, ensure_bytes, str_to_bytes\n\nfrom celery.app.defaults import DEFAULT_SECURITY_DIGEST\nfrom celery.utils.serialization import b64decode, b64encode\n\nfrom .certificate import Certificate, FSCertStore\nfrom .key import PrivateKey\nfrom .utils import get_digest_algorithm, reraise_errors\n\n__all__ = ('SecureSerializer', 'register_auth')\n\n\nclass SecureSerializer:\n    \"\"\"Signed serializer.\"\"\"\n\n    def __init__(self, key=None, cert=None, cert_store=None,\n                 digest=DEFAULT_SECURITY_DIGEST, serializer='json'):\n        self._key = key\n        self._cert = cert\n        self._cert_store = cert_store\n        self._digest = get_digest_algorithm(digest)\n        self._serializer = serializer\n\n    def serialize(self, data):\n        \"\"\"Serialize data structure into string.\"\"\"\n        assert self._key is not None\n        assert self._cert is not None\n        with reraise_errors('Unable to serialize: {0!r}', (Exception,)):\n            content_type, content_encoding, body = dumps(\n                bytes_to_str(data), serializer=self._serializer)\n            # What we sign is the serialized body, not the body itself.\n            # this way the receiver doesn't have to decode the contents\n            # to verify the signature (and thus avoiding potential flaws\n            # in the decoding step).\n            body = ensure_bytes(body)\n            return self._pack(body, content_type, content_encoding,\n                              signature=self._key.sign(body, self._digest),\n                              signer=self._cert.get_id())\n\n    def deserialize(self, data):\n        \"\"\"Deserialize data structure from string.\"\"\"\n        assert self._cert_store is not None\n        with reraise_errors('Unable to deserialize: {0!r}', (Exception,)):\n            payload = self._unpack(data)\n            signature, signer, body = (payload['signature'],\n                                       payload['signer'],\n                                       payload['body'])\n            self._cert_store[signer].verify(body, signature, self._digest)\n        return loads(bytes_to_str(body), payload['content_type'],\n                     payload['content_encoding'], force=True)\n\n    def _pack(self, body, content_type, content_encoding, signer, signature,\n              sep=str_to_bytes('\\x00\\x01')):\n        fields = sep.join(\n            ensure_bytes(s) for s in [signer, signature, content_type,\n                                      content_encoding, body]\n        )\n        return b64encode(fields)\n\n    def _unpack(self, payload, sep=str_to_bytes('\\x00\\x01')):\n        raw_payload = b64decode(ensure_bytes(payload))\n        first_sep = raw_payload.find(sep)\n\n        signer = raw_payload[:first_sep]\n        signer_cert = self._cert_store[signer]\n\n        # shift 3 bits right to get signature length\n        # 2048bit rsa key has a signature length of 256\n        # 4096bit rsa key has a signature length of 512\n        sig_len = signer_cert.get_pubkey().key_size >> 3\n        sep_len = len(sep)\n        signature_start_position = first_sep + sep_len\n        signature_end_position = signature_start_position + sig_len\n        signature = raw_payload[\n            signature_start_position:signature_end_position\n        ]\n\n        v = raw_payload[signature_end_position + sep_len:].split(sep)\n\n        return {\n            'signer': signer,\n            'signature': signature,\n            'content_type': bytes_to_str(v[0]),\n            'content_encoding': bytes_to_str(v[1]),\n            'body': bytes_to_str(v[2]),\n        }\n\n\ndef register_auth(key=None, key_password=None, cert=None, store=None,\n                  digest=DEFAULT_SECURITY_DIGEST,\n                  serializer='json'):\n    \"\"\"Register security serializer.\"\"\"\n    s = SecureSerializer(key and PrivateKey(key, password=key_password),\n                         cert and Certificate(cert),\n                         store and FSCertStore(store),\n                         digest, serializer=serializer)\n    registry.register('auth', s.serialize, s.deserialize,\n                      content_type='application/data',\n                      content_encoding='utf-8')\n", "path": "celery/security/serialization.py"}], "after_files": [{"content": "\"\"\"Secure serializer.\"\"\"\nfrom kombu.serialization import dumps, loads, registry\nfrom kombu.utils.encoding import bytes_to_str, ensure_bytes, str_to_bytes\n\nfrom celery.app.defaults import DEFAULT_SECURITY_DIGEST\nfrom celery.utils.serialization import b64decode, b64encode\n\nfrom .certificate import Certificate, FSCertStore\nfrom .key import PrivateKey\nfrom .utils import get_digest_algorithm, reraise_errors\n\n__all__ = ('SecureSerializer', 'register_auth')\n\n\nclass SecureSerializer:\n    \"\"\"Signed serializer.\"\"\"\n\n    def __init__(self, key=None, cert=None, cert_store=None,\n                 digest=DEFAULT_SECURITY_DIGEST, serializer='json'):\n        self._key = key\n        self._cert = cert\n        self._cert_store = cert_store\n        self._digest = get_digest_algorithm(digest)\n        self._serializer = serializer\n\n    def serialize(self, data):\n        \"\"\"Serialize data structure into string.\"\"\"\n        assert self._key is not None\n        assert self._cert is not None\n        with reraise_errors('Unable to serialize: {0!r}', (Exception,)):\n            content_type, content_encoding, body = dumps(\n                data, serializer=self._serializer)\n\n            # What we sign is the serialized body, not the body itself.\n            # this way the receiver doesn't have to decode the contents\n            # to verify the signature (and thus avoiding potential flaws\n            # in the decoding step).\n            body = ensure_bytes(body)\n            return self._pack(body, content_type, content_encoding,\n                              signature=self._key.sign(body, self._digest),\n                              signer=self._cert.get_id())\n\n    def deserialize(self, data):\n        \"\"\"Deserialize data structure from string.\"\"\"\n        assert self._cert_store is not None\n        with reraise_errors('Unable to deserialize: {0!r}', (Exception,)):\n            payload = self._unpack(data)\n            signature, signer, body = (payload['signature'],\n                                       payload['signer'],\n                                       payload['body'])\n            self._cert_store[signer].verify(body, signature, self._digest)\n        return loads(body, payload['content_type'],\n                     payload['content_encoding'], force=True)\n\n    def _pack(self, body, content_type, content_encoding, signer, signature,\n              sep=str_to_bytes('\\x00\\x01')):\n        fields = sep.join(\n            ensure_bytes(s) for s in [signer, signature, content_type,\n                                      content_encoding, body]\n        )\n        return b64encode(fields)\n\n    def _unpack(self, payload, sep=str_to_bytes('\\x00\\x01')):\n        raw_payload = b64decode(ensure_bytes(payload))\n        first_sep = raw_payload.find(sep)\n\n        signer = raw_payload[:first_sep]\n        signer_cert = self._cert_store[signer]\n\n        # shift 3 bits right to get signature length\n        # 2048bit rsa key has a signature length of 256\n        # 4096bit rsa key has a signature length of 512\n        sig_len = signer_cert.get_pubkey().key_size >> 3\n        sep_len = len(sep)\n        signature_start_position = first_sep + sep_len\n        signature_end_position = signature_start_position + sig_len\n        signature = raw_payload[\n            signature_start_position:signature_end_position\n        ]\n\n        v = raw_payload[signature_end_position + sep_len:].split(sep)\n\n        return {\n            'signer': signer,\n            'signature': signature,\n            'content_type': bytes_to_str(v[0]),\n            'content_encoding': bytes_to_str(v[1]),\n            'body': v[2],\n        }\n\n\ndef register_auth(key=None, key_password=None, cert=None, store=None,\n                  digest=DEFAULT_SECURITY_DIGEST,\n                  serializer='json'):\n    \"\"\"Register security serializer.\"\"\"\n    s = SecureSerializer(key and PrivateKey(key, password=key_password),\n                         cert and Certificate(cert),\n                         store and FSCertStore(store),\n                         digest, serializer=serializer)\n    registry.register('auth', s.serialize, s.deserialize,\n                      content_type='application/data',\n                      content_encoding='utf-8')\n", "path": "celery/security/serialization.py"}]}