Merge pull request #115 from dhermes/convert-pkcs12-to-pem

Adding protected method to convert PKCS12 key to PEM.
This commit is contained in:
Craig Citro
2015-01-15 00:09:02 -08:00
3 changed files with 99 additions and 1 deletions

View File

@@ -138,9 +138,29 @@ try:
pkey = crypto.load_pkcs12(key, password).get_privatekey()
return OpenSSLSigner(pkey)
def pkcs12_key_as_pem(private_key_text, private_key_password):
"""Convert the contents of a PKCS12 key to PEM using OpenSSL.
Args:
private_key_text: String. Private key.
private_key_password: String. Password for PKCS12.
Returns:
String. PEM contents of ``private_key_text``.
"""
decoded_body = base64.b64decode(private_key_text)
if isinstance(private_key_password, six.string_types):
private_key_password = private_key_password.encode('ascii')
pkcs12 = crypto.load_pkcs12(decoded_body, private_key_password)
return crypto.dump_privatekey(crypto.FILETYPE_PEM,
pkcs12.get_privatekey())
except ImportError:
OpenSSLVerifier = None
OpenSSLSigner = None
def pkcs12_key_as_pem(*args, **kwargs):
raise NotImplementedError('pkcs12_key_as_pem requires OpenSSL.')
try:

73
tests/test_crypt.py Normal file
View File

@@ -0,0 +1,73 @@
# Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import mock
import os
import sys
import unittest
try:
reload
except NameError:
# For Python3 (though importlib should be used, silly 3.3).
from imp import reload
from oauth2client.client import HAS_OPENSSL
from oauth2client.client import SignedJwtAssertionCredentials
from oauth2client import crypt
def datafile(filename):
f = open(os.path.join(os.path.dirname(__file__), 'data', filename), 'rb')
data = f.read()
f.close()
return data
class Test_pkcs12_key_as_pem(unittest.TestCase):
def _make_signed_jwt_creds(self, private_key_file='privatekey.p12',
private_key=None):
private_key = private_key or datafile(private_key_file)
return SignedJwtAssertionCredentials(
'some_account@example.com',
private_key,
scope='read+write',
sub='joe@example.org')
def test_succeeds(self):
self.assertEqual(True, HAS_OPENSSL)
credentials = self._make_signed_jwt_creds()
pem_contents = crypt.pkcs12_key_as_pem(credentials.private_key,
credentials.private_key_password)
pkcs12_key_as_pem = datafile('pem_from_pkcs12.pem')
pkcs12_key_as_pem = crypt._parse_pem_key(pkcs12_key_as_pem)
self.assertEqual(pem_contents, pkcs12_key_as_pem)
def test_without_openssl(self):
openssl_mod = sys.modules['OpenSSL']
try:
sys.modules['OpenSSL'] = None
reload(crypt)
self.assertRaises(NotImplementedError, crypt.pkcs12_key_as_pem,
'FOO', 'BAR')
finally:
sys.modules['OpenSSL'] = openssl_mod
reload(crypt)
def test_with_nonsense_key(self):
credentials = self._make_signed_jwt_creds(private_key=b'NOT_A_KEY')
self.assertRaises(crypt.crypto.Error, crypt.pkcs12_key_as_pem,
credentials.private_key, credentials.private_key_password)

View File

@@ -23,19 +23,21 @@ Unit tests for oauth2client.
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import os
import mock
import sys
import tempfile
import time
import unittest
from .http_mock import HttpMockSequence
from oauth2client import crypt
from oauth2client import client
from oauth2client.client import Credentials
from oauth2client.client import SignedJwtAssertionCredentials
from oauth2client.client import VerifyJwtTokenError
from oauth2client.client import verify_id_token
from oauth2client.client import HAS_OPENSSL
from oauth2client.client import HAS_CRYPTO
from oauth2client import crypt
from oauth2client.file import Storage
@@ -47,6 +49,7 @@ def datafile(filename):
class CryptTests(unittest.TestCase):
def setUp(self):
self.format = 'p12'
self.signer = crypt.OpenSSLSigner
@@ -291,6 +294,7 @@ class PEMSignedJwtAssertionCredentialsPyCryptoTests(
class PKCSSignedJwtAssertionCredentialsPyCryptoTests(unittest.TestCase):
def test_for_failure(self):
crypt.Signer = crypt.PyCryptoSigner
private_key = datafile('privatekey.p12')
@@ -311,5 +315,6 @@ class TestHasOpenSSLFlag(unittest.TestCase):
self.assertEqual(True, HAS_OPENSSL)
self.assertEqual(True, HAS_CRYPTO)
if __name__ == '__main__':
unittest.main()