|
| 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 | + |
| 15 | +import rsa |
| 16 | + |
| 17 | +from pyasn1.codec.der import decoder |
| 18 | +from pyasn1.type import univ |
| 19 | +from rsa import pkcs1 |
| 20 | + |
| 21 | + |
| 22 | +# python-rsa lib hashes all messages it signs. ADB does it already, we just |
| 23 | +# need to slap a signature on top of already hashed message. Introduce "fake" |
| 24 | +# hashing algo for this. |
| 25 | +class _Accum(object): |
| 26 | + def __init__(self): |
| 27 | + self._buf = '' |
| 28 | + def update(self, msg): |
| 29 | + self._buf += msg |
| 30 | + def digest(self): |
| 31 | + return self._buf |
| 32 | +pkcs1.HASH_METHODS['SHA-1-PREHASHED'] = _Accum |
| 33 | +pkcs1.HASH_ASN1['SHA-1-PREHASHED'] = pkcs1.HASH_ASN1['SHA-1'] |
| 34 | + |
| 35 | + |
| 36 | +def _load_rsa_private_key(pem): |
| 37 | + """PEM encoded PKCS#8 private key -> rsa.PrivateKey.""" |
| 38 | + # ADB uses private RSA keys in pkcs#8 format. 'rsa' library doesn't support |
| 39 | + # them natively. Do some ASN unwrapping to extract naked RSA key |
| 40 | + # (in der-encoded form). See https://www.ietf.org/rfc/rfc2313.txt. |
| 41 | + # Also http://superuser.com/a/606266. |
| 42 | + try: |
| 43 | + der = rsa.pem.load_pem(pem, 'PRIVATE KEY') |
| 44 | + keyinfo, _ = decoder.decode(der) |
| 45 | + if keyinfo[1][0] != univ.ObjectIdentifier( |
| 46 | + '1.2.840.113549.1.1.1'): # pragma: no cover |
| 47 | + raise ValueError('Not a DER-encoded OpenSSL private RSA key') |
| 48 | + private_key_der = keyinfo[2].asOctets() |
| 49 | + except IndexError: # pragma: no cover |
| 50 | + raise ValueError('Not a DER-encoded OpenSSL private RSA key') |
| 51 | + return rsa.PrivateKey.load_pkcs1(private_key_der, format='DER') |
| 52 | + |
| 53 | + |
| 54 | +class PythonRSASigner(object): |
| 55 | + """Implements adb_protocol.AuthSigner using http://stuvel.eu/rsa.""" |
| 56 | + def __init__(self, pub, priv): |
| 57 | + self.priv_key = _load_rsa_private_key(priv) |
| 58 | + self.pub_key = pub |
| 59 | + |
| 60 | + def Sign(self, data): |
| 61 | + return rsa.sign(data, self.priv_key, 'SHA-1-PREHASHED') |
| 62 | + |
| 63 | + def GetPublicKey(self): |
| 64 | + return self.pub_key |
0 commit comments