sign_pythonrsa.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # Copyright 2014 Google Inc. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import rsa
  15. from pyasn1.codec.der import decoder
  16. from pyasn1.type import univ
  17. from rsa import pkcs1
  18. # python-rsa lib hashes all messages it signs. ADB does it already, we just
  19. # need to slap a signature on top of already hashed message. Introduce "fake"
  20. # hashing algo for this.
  21. class _Accum(object):
  22. def __init__(self):
  23. self._buf = b''
  24. def update(self, msg):
  25. self._buf += msg
  26. def digest(self):
  27. return self._buf
  28. pkcs1.HASH_METHODS['SHA-1-PREHASHED'] = _Accum
  29. pkcs1.HASH_ASN1['SHA-1-PREHASHED'] = pkcs1.HASH_ASN1['SHA-1']
  30. def _load_rsa_private_key(pem):
  31. """PEM encoded PKCS#8 private key -> rsa.PrivateKey."""
  32. # ADB uses private RSA keys in pkcs#8 format. 'rsa' library doesn't support
  33. # them natively. Do some ASN unwrapping to extract naked RSA key
  34. # (in der-encoded form). See https://www.ietf.org/rfc/rfc2313.txt.
  35. # Also http://superuser.com/a/606266.
  36. try:
  37. der = rsa.pem.load_pem(pem, 'PRIVATE KEY')
  38. keyinfo, _ = decoder.decode(der)
  39. if keyinfo[1][0] != univ.ObjectIdentifier(
  40. '1.2.840.113549.1.1.1'): # pragma: no cover
  41. raise ValueError('Not a DER-encoded OpenSSL private RSA key')
  42. private_key_der = keyinfo[2].asOctets()
  43. except IndexError: # pragma: no cover
  44. raise ValueError('Not a DER-encoded OpenSSL private RSA key')
  45. return rsa.PrivateKey.load_pkcs1(private_key_der, format='DER')
  46. class PythonRSASigner(object):
  47. """Implements adb_protocol.AuthSigner using http://stuvel.eu/rsa."""
  48. @classmethod
  49. def FromRSAKeyPath(cls, rsa_key_path):
  50. with open(rsa_key_path + '.pub') as f:
  51. pub = f.read()
  52. with open(rsa_key_path) as f:
  53. priv = f.read()
  54. return cls(pub, priv)
  55. def __init__(self, pub=None, priv=None):
  56. self.priv_key = _load_rsa_private_key(priv)
  57. self.pub_key = pub
  58. def Sign(self, data):
  59. return rsa.sign(data, self.priv_key, 'SHA-1-PREHASHED')
  60. def GetPublicKey(self):
  61. return self.pub_key