Revert "Remove DSA support from keymaster."

This reverts commit 5e0579c2d4437b6f3c03872a643d12cb08a7bc79.
diff --git a/Makefile b/Makefile
index 439fb4d..c308942 100644
--- a/Makefile
+++ b/Makefile
@@ -29,6 +29,8 @@
 	asymmetric_key.cpp \
 	authorization_set.cpp \
 	authorization_set_test.cpp \
+	dsa_key.cpp \
+	dsa_operation.cpp \
 	ecdsa_key.cpp \
 	ecdsa_operation.cpp \
 	google_keymaster.cpp \
@@ -127,6 +129,8 @@
 	aes_key.o \
 	asymmetric_key.o \
 	authorization_set.o \
+	dsa_key.o \
+	dsa_operation.o \
 	ecdsa_key.o \
 	ecdsa_operation.o \
 	google_keymaster.o \
diff --git a/dsa_key.cpp b/dsa_key.cpp
new file mode 100644
index 0000000..973879b
--- /dev/null
+++ b/dsa_key.cpp
@@ -0,0 +1,225 @@
+/*
+ * Copyright 2014 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#include "dsa_key.h"
+#include "dsa_operation.h"
+#include "openssl_utils.h"
+#include "unencrypted_key_blob.h"
+
+namespace keymaster {
+
+const uint32_t DSA_DEFAULT_KEY_SIZE = 2048;
+
+template <keymaster_tag_t Tag>
+static void GetDsaParamData(const AuthorizationSet& auths, TypedTag<KM_BIGNUM, Tag> tag,
+                            keymaster_blob_t* blob) {
+    if (!auths.GetTagValue(tag, blob))
+        blob->data = NULL;
+}
+
+// Store the specified DSA param in auths
+template <keymaster_tag_t Tag>
+static void SetDsaParamData(AuthorizationSet* auths, TypedTag<KM_BIGNUM, Tag> tag, BIGNUM* number) {
+    keymaster_blob_t blob;
+    convert_bn_to_blob(number, &blob);
+    auths->push_back(Authorization(tag, blob));
+    delete[] blob.data;
+}
+
+DsaKey* DsaKey::GenerateKey(const AuthorizationSet& key_description, const Logger& logger,
+                            keymaster_error_t* error) {
+    if (!error)
+        return NULL;
+
+    AuthorizationSet authorizations(key_description);
+
+    uint32_t key_size = DSA_DEFAULT_KEY_SIZE;
+    if (!authorizations.GetTagValue(TAG_KEY_SIZE, &key_size))
+        authorizations.push_back(Authorization(TAG_KEY_SIZE, key_size));
+
+    UniquePtr<DSA, DSA_Delete> dsa_key(DSA_new());
+    UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(EVP_PKEY_new());
+    if (dsa_key.get() == NULL || pkey.get() == NULL) {
+        *error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
+        return NULL;
+    }
+
+    // If anything goes wrong in the next section, it's a param problem.
+    *error = KM_ERROR_INVALID_DSA_PARAMS;
+
+    keymaster_blob_t g_blob;
+    keymaster_blob_t p_blob;
+    keymaster_blob_t q_blob;
+    GetDsaParamData(authorizations, TAG_DSA_GENERATOR, &g_blob);
+    GetDsaParamData(authorizations, TAG_DSA_P, &p_blob);
+    GetDsaParamData(authorizations, TAG_DSA_Q, &q_blob);
+
+    if (g_blob.data == NULL && p_blob.data == NULL && q_blob.data == NULL) {
+        logger.info("DSA parameters unspecified, generating them for key size %d", key_size);
+        if (!DSA_generate_parameters_ex(dsa_key.get(), key_size, NULL /* seed */, 0 /* seed_len */,
+                                        NULL /* counter_ret */, NULL /* h_ret */,
+                                        NULL /* callback */)) {
+            logger.severe("DSA parameter generation failed.");
+            return NULL;
+        }
+
+        SetDsaParamData(&authorizations, TAG_DSA_GENERATOR, dsa_key->g);
+        SetDsaParamData(&authorizations, TAG_DSA_P, dsa_key->p);
+        SetDsaParamData(&authorizations, TAG_DSA_Q, dsa_key->q);
+    } else if (g_blob.data == NULL || p_blob.data == NULL || q_blob.data == NULL) {
+        logger.severe("Some DSA parameters provided.  Provide all or none");
+        return NULL;
+    } else {
+        // All params provided. Use them.
+        dsa_key->g = BN_bin2bn(g_blob.data, g_blob.data_length, NULL);
+        dsa_key->p = BN_bin2bn(p_blob.data, p_blob.data_length, NULL);
+        dsa_key->q = BN_bin2bn(q_blob.data, q_blob.data_length, NULL);
+        if (dsa_key->g == NULL || dsa_key->p == NULL || dsa_key->q == NULL) {
+            return NULL;
+        }
+    }
+
+    if (!DSA_generate_key(dsa_key.get())) {
+        *error = KM_ERROR_UNKNOWN_ERROR;
+        return NULL;
+    }
+
+    DsaKey* new_key = new DsaKey(dsa_key.release(), authorizations, logger);
+    *error = new_key ? KM_ERROR_OK : KM_ERROR_MEMORY_ALLOCATION_FAILED;
+    return new_key;
+}
+
+template <keymaster_tag_t T>
+keymaster_error_t GetOrCheckDsaParam(TypedTag<KM_BIGNUM, T> tag, BIGNUM* bn,
+                                     AuthorizationSet* auths) {
+    keymaster_blob_t blob;
+    if (auths->GetTagValue(tag, &blob)) {
+        // value specified, make sure it matches
+        UniquePtr<BIGNUM, BIGNUM_Delete> extracted_bn(BN_bin2bn(blob.data, blob.data_length, NULL));
+        if (extracted_bn.get() == NULL)
+            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
+        if (BN_cmp(extracted_bn.get(), bn) != 0)
+            return KM_ERROR_IMPORT_PARAMETER_MISMATCH;
+    } else {
+        // value not specified, add it
+        UniquePtr<uint8_t[]> data(new uint8_t[BN_num_bytes(bn)]);
+        BN_bn2bin(bn, data.get());
+        auths->push_back(tag, data.get(), BN_num_bytes(bn));
+    }
+    return KM_ERROR_OK;
+}
+
+static size_t calculate_key_size_in_bits(DSA* dsa_key) {
+    // Openssl provides no convenient way to get a DSA key size, but dsa_key->p is L bits long.
+    // There may be some leading zeros that mess up this calculation, but DSA key sizes are also
+    // constrained to be multiples of 64 bits.  So the key size is the bit length of p rounded up to
+    // the nearest 64.
+    return ((BN_num_bytes(dsa_key->p) * 8) + 63) / 64 * 64;
+}
+
+/* static */
+DsaKey* DsaKey::ImportKey(const AuthorizationSet& key_description, EVP_PKEY* pkey,
+                          const Logger& logger, keymaster_error_t* error) {
+    if (!error)
+        return NULL;
+    *error = KM_ERROR_UNKNOWN_ERROR;
+
+    UniquePtr<DSA, DSA_Delete> dsa_key(EVP_PKEY_get1_DSA(pkey));
+    if (!dsa_key.get())
+        return NULL;
+
+    AuthorizationSet authorizations(key_description);
+
+    *error = GetOrCheckDsaParam(TAG_DSA_GENERATOR, dsa_key->g, &authorizations);
+    if (*error != KM_ERROR_OK)
+        return NULL;
+
+    *error = GetOrCheckDsaParam(TAG_DSA_P, dsa_key->p, &authorizations);
+    if (*error != KM_ERROR_OK)
+        return NULL;
+
+    *error = GetOrCheckDsaParam(TAG_DSA_Q, dsa_key->q, &authorizations);
+    if (*error != KM_ERROR_OK)
+        return NULL;
+
+    uint32_t key_size_in_bits;
+    if (authorizations.GetTagValue(TAG_KEY_SIZE, &key_size_in_bits)) {
+        // key_bits specified, make sure it matches the key.
+        if (key_size_in_bits != calculate_key_size_in_bits(dsa_key.get())) {
+            *error = KM_ERROR_IMPORT_PARAMETER_MISMATCH;
+            return NULL;
+        }
+    } else {
+        // key_size_bits not specified, add it.
+        authorizations.push_back(TAG_KEY_SIZE, calculate_key_size_in_bits(dsa_key.get()));
+    }
+
+    keymaster_algorithm_t algorithm;
+    if (authorizations.GetTagValue(TAG_ALGORITHM, &algorithm)) {
+        if (algorithm != KM_ALGORITHM_DSA) {
+            *error = KM_ERROR_IMPORT_PARAMETER_MISMATCH;
+            return NULL;
+        }
+    } else {
+        authorizations.push_back(TAG_ALGORITHM, KM_ALGORITHM_DSA);
+    }
+
+    // Don't bother with the other parameters.  If the necessary padding, digest, purpose, etc. are
+    // missing, the error will be diagnosed when the key is used (when auth checking is
+    // implemented).
+    *error = KM_ERROR_OK;
+    return new DsaKey(dsa_key.release(), authorizations, logger);
+}
+
+DsaKey::DsaKey(const UnencryptedKeyBlob& blob, const Logger& logger, keymaster_error_t* error)
+    : AsymmetricKey(blob, logger) {
+    if (error)
+        *error = LoadKey(blob);
+}
+
+Operation* DsaKey::CreateOperation(keymaster_purpose_t purpose, keymaster_error_t* error) {
+    keymaster_digest_t digest = KM_DIGEST_NONE;
+    if (!authorizations().GetTagValue(TAG_DIGEST, &digest) || digest != KM_DIGEST_NONE) {
+        *error = KM_ERROR_UNSUPPORTED_DIGEST;
+        return NULL;
+    }
+
+    Operation* op;
+    switch (purpose) {
+    case KM_PURPOSE_SIGN:
+        op = new DsaSignOperation(purpose, logger_, digest, dsa_key_.release());
+        break;
+    case KM_PURPOSE_VERIFY:
+        op = new DsaVerifyOperation(purpose, logger_, digest, dsa_key_.release());
+        break;
+    default:
+        *error = KM_ERROR_INCOMPATIBLE_PURPOSE;
+        return NULL;
+    }
+    *error = op ? KM_ERROR_OK : KM_ERROR_MEMORY_ALLOCATION_FAILED;
+    return op;
+}
+
+bool DsaKey::EvpToInternal(const EVP_PKEY* pkey) {
+    dsa_key_.reset(EVP_PKEY_get1_DSA(const_cast<EVP_PKEY*>(pkey)));
+    return dsa_key_.get() != NULL;
+}
+
+bool DsaKey::InternalToEvp(EVP_PKEY* pkey) const {
+    return EVP_PKEY_set1_DSA(pkey, dsa_key_.get()) == 1;
+}
+
+}  // namespace keymaster
diff --git a/dsa_key.h b/dsa_key.h
new file mode 100644
index 0000000..93a04a9
--- /dev/null
+++ b/dsa_key.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2014 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#ifndef SYSTEM_KEYMASTER_DSA_KEY_H_
+#define SYSTEM_KEYMASTER_DSA_KEY_H_
+
+#include <openssl/dsa.h>
+
+#include "asymmetric_key.h"
+
+namespace keymaster {
+
+class DsaKey : public AsymmetricKey {
+  public:
+    static DsaKey* GenerateKey(const AuthorizationSet& key_description, const Logger& logger,
+                               keymaster_error_t* error);
+    static DsaKey* ImportKey(const AuthorizationSet& key_description, EVP_PKEY* pkey,
+                             const Logger& logger, keymaster_error_t* error);
+    DsaKey(const UnencryptedKeyBlob& blob, const Logger& logger, keymaster_error_t* error);
+
+    virtual Operation* CreateOperation(keymaster_purpose_t purpose, keymaster_error_t* error);
+
+  private:
+    DsaKey(DSA* dsa_key, const AuthorizationSet auths, const Logger& logger)
+        : AsymmetricKey(auths, logger), dsa_key_(dsa_key) {}
+
+    virtual int evp_key_type() { return EVP_PKEY_DSA; }
+    virtual bool InternalToEvp(EVP_PKEY* pkey) const;
+    virtual bool EvpToInternal(const EVP_PKEY* pkey);
+
+    struct DSA_Delete {
+        void operator()(DSA* p) { DSA_free(p); }
+    };
+
+    UniquePtr<DSA, DSA_Delete> dsa_key_;
+};
+
+}  // namespace keymaster
+
+#endif  // SYSTEM_KEYMASTER_DSA_KEY_H_
diff --git a/dsa_operation.cpp b/dsa_operation.cpp
new file mode 100644
index 0000000..dc64343
--- /dev/null
+++ b/dsa_operation.cpp
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2014 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#include <openssl/bn.h>
+
+#include "dsa_operation.h"
+#include "openssl_utils.h"
+
+namespace keymaster {
+
+DsaOperation::~DsaOperation() {
+    if (dsa_key_ != NULL)
+        DSA_free(dsa_key_);
+}
+
+keymaster_error_t DsaOperation::Update(const Buffer& input, Buffer* /* output */) {
+    switch (purpose()) {
+    default:
+        return KM_ERROR_UNIMPLEMENTED;
+    case KM_PURPOSE_SIGN:
+    case KM_PURPOSE_VERIFY:
+        return StoreData(input);
+    }
+}
+
+keymaster_error_t DsaOperation::StoreData(const Buffer& input) {
+    if (!data_.reserve(data_.available_read() + input.available_read()) ||
+        !data_.write(input.peek_read(), input.available_read()))
+        return KM_ERROR_INVALID_INPUT_LENGTH;
+    return KM_ERROR_OK;
+}
+
+keymaster_error_t DsaSignOperation::Finish(const Buffer& /* signature */, Buffer* output) {
+    output->Reinitialize(DSA_size(dsa_key_));
+    unsigned int siglen;
+    if (!DSA_sign(0 /* type -- ignored */, data_.peek_read(), data_.available_read(),
+                  output->peek_write(), &siglen, dsa_key_))
+        return KM_ERROR_UNKNOWN_ERROR;
+    output->advance_write(siglen);
+    return KM_ERROR_OK;
+}
+
+keymaster_error_t DsaVerifyOperation::Finish(const Buffer& signature, Buffer* /* output */) {
+    if ((int)data_.available_read() != DSA_size(dsa_key_))
+        return KM_ERROR_INVALID_INPUT_LENGTH;
+
+    int result = DSA_verify(0 /* type -- ignored */, data_.peek_read(), data_.available_read(),
+                            signature.peek_read(), signature.available_read(), dsa_key_);
+    if (result < 0)
+        return KM_ERROR_UNKNOWN_ERROR;
+    else if (result == 0)
+        return KM_ERROR_VERIFICATION_FAILED;
+    else
+        return KM_ERROR_OK;
+}
+
+}  // namespace keymaster
diff --git a/dsa_operation.h b/dsa_operation.h
new file mode 100644
index 0000000..054932d
--- /dev/null
+++ b/dsa_operation.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2014 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#ifndef SYSTEM_KEYMASTER_DSA_OPERATION_H_
+#define SYSTEM_KEYMASTER_DSA_OPERATION_H_
+
+#include <openssl/dsa.h>
+
+#include <UniquePtr.h>
+
+#include <keymaster/key_blob.h>
+
+#include "operation.h"
+
+namespace keymaster {
+
+class DsaOperation : public Operation {
+  public:
+    DsaOperation(keymaster_purpose_t purpose, const Logger& logger, keymaster_digest_t digest,
+                 DSA* key)
+        : Operation(purpose, logger), dsa_key_(key), digest_(digest) {}
+    ~DsaOperation();
+
+    virtual keymaster_error_t Begin() { return KM_ERROR_OK; }
+    virtual keymaster_error_t Update(const Buffer& input, Buffer* output);
+    virtual keymaster_error_t Abort() { return KM_ERROR_OK; }
+
+  protected:
+    keymaster_error_t StoreData(const Buffer& input);
+
+    DSA* dsa_key_;
+    keymaster_digest_t digest_;
+    Buffer data_;
+};
+
+class DsaSignOperation : public DsaOperation {
+  public:
+    DsaSignOperation(keymaster_purpose_t purpose, const Logger& logger, keymaster_digest_t digest,
+                     DSA* key)
+        : DsaOperation(purpose, logger, digest, key) {}
+    virtual keymaster_error_t Finish(const Buffer& signature, Buffer* output);
+};
+
+class DsaVerifyOperation : public DsaOperation {
+  public:
+    DsaVerifyOperation(keymaster_purpose_t purpose, const Logger& logger, keymaster_digest_t digest,
+                       DSA* key)
+        : DsaOperation(purpose, logger, digest, key) {}
+    virtual keymaster_error_t Finish(const Buffer& signature, Buffer* output);
+};
+
+}  // namespace keymaster
+
+#endif  // SYSTEM_KEYMASTER_DSA_OPERATION_H_
diff --git a/dsa_privkey_pk8.der b/dsa_privkey_pk8.der
new file mode 100644
index 0000000..2786bc7
--- /dev/null
+++ b/dsa_privkey_pk8.der
Binary files differ
diff --git a/google_keymaster_test.cpp b/google_keymaster_test.cpp
index adc931e..4dca97a 100644
--- a/google_keymaster_test.cpp
+++ b/google_keymaster_test.cpp
@@ -268,6 +268,78 @@
     EXPECT_TRUE(contains(rsp_.unenforced, TAG_KEY_SIZE, 2048));
 }
 
+TEST_F(NewKeyGeneration, Dsa) {
+    req_.key_description.push_back(Authorization(TAG_ALGORITHM, KM_ALGORITHM_DSA));
+    req_.key_description.push_back(Authorization(TAG_KEY_SIZE, 256));
+    device.GenerateKey(req_, &rsp_);
+
+    CheckBaseParams(rsp_);
+
+    // Check specified tags are all present in unenforced characteristics
+    EXPECT_TRUE(contains(rsp_.unenforced, TAG_ALGORITHM, KM_ALGORITHM_DSA));
+    EXPECT_TRUE(contains(rsp_.unenforced, TAG_KEY_SIZE, 256));
+
+    // Generator should have created DSA params.
+    keymaster_blob_t g, p, q;
+    EXPECT_TRUE(rsp_.unenforced.GetTagValue(TAG_DSA_GENERATOR, &g));
+    EXPECT_TRUE(rsp_.unenforced.GetTagValue(TAG_DSA_P, &p));
+    EXPECT_TRUE(rsp_.unenforced.GetTagValue(TAG_DSA_Q, &q));
+    EXPECT_TRUE(g.data_length >= 63 && g.data_length <= 64);
+    EXPECT_EQ(64U, p.data_length);
+    EXPECT_EQ(20U, q.data_length);
+}
+
+TEST_F(NewKeyGeneration, DsaDefaultSize) {
+    req_.key_description.push_back(Authorization(TAG_ALGORITHM, KM_ALGORITHM_DSA));
+    device.GenerateKey(req_, &rsp_);
+
+    CheckBaseParams(rsp_);
+
+    // Check specified tags are all present in unenforced characteristics
+    EXPECT_TRUE(contains(rsp_.unenforced, TAG_ALGORITHM, KM_ALGORITHM_DSA));
+
+    // Now check that unspecified, defaulted tags are correct.
+    EXPECT_TRUE(contains(rsp_.unenforced, TAG_KEY_SIZE, 2048));
+    keymaster_blob_t g, p, q;
+    EXPECT_TRUE(rsp_.unenforced.GetTagValue(TAG_DSA_GENERATOR, &g));
+    EXPECT_TRUE(rsp_.unenforced.GetTagValue(TAG_DSA_P, &p));
+    EXPECT_TRUE(rsp_.unenforced.GetTagValue(TAG_DSA_Q, &q));
+    EXPECT_TRUE(g.data_length >= 255 && g.data_length <= 256);
+    EXPECT_EQ(256U, p.data_length);
+    EXPECT_EQ(32U, q.data_length);
+}
+
+TEST_F(NewKeyGeneration, Dsa_ParamsSpecified) {
+    req_.key_description.push_back(Authorization(TAG_ALGORITHM, KM_ALGORITHM_DSA));
+    req_.key_description.push_back(Authorization(TAG_KEY_SIZE, 256));
+    req_.key_description.push_back(Authorization(TAG_DSA_GENERATOR, dsa_g, array_size(dsa_g)));
+    req_.key_description.push_back(Authorization(TAG_DSA_P, dsa_p, array_size(dsa_p)));
+    req_.key_description.push_back(Authorization(TAG_DSA_Q, dsa_q, array_size(dsa_q)));
+    device.GenerateKey(req_, &rsp_);
+
+    CheckBaseParams(rsp_);
+
+    // Check specified tags are all present in unenforced characteristics
+    EXPECT_TRUE(contains(rsp_.unenforced, TAG_ALGORITHM, KM_ALGORITHM_DSA));
+    EXPECT_TRUE(contains(rsp_.unenforced, TAG_KEY_SIZE, 256));
+    EXPECT_TRUE(contains(rsp_.unenforced, TAG_DSA_GENERATOR,
+                         std::string(reinterpret_cast<const char*>(dsa_g), array_size(dsa_g))));
+    EXPECT_TRUE(contains(rsp_.unenforced, TAG_DSA_P,
+                         std::string(reinterpret_cast<const char*>(dsa_p), array_size(dsa_p))));
+    EXPECT_TRUE(contains(rsp_.unenforced, TAG_DSA_Q,
+                         std::string(reinterpret_cast<const char*>(dsa_q), array_size(dsa_q))));
+}
+
+TEST_F(NewKeyGeneration, Dsa_SomeParamsSpecified) {
+    req_.key_description.push_back(Authorization(TAG_ALGORITHM, KM_ALGORITHM_DSA));
+    req_.key_description.push_back(Authorization(TAG_KEY_SIZE, 256));
+    req_.key_description.push_back(Authorization(TAG_DSA_P, dsa_p, array_size(dsa_p)));
+    req_.key_description.push_back(Authorization(TAG_DSA_Q, dsa_q, array_size(dsa_q)));
+    device.GenerateKey(req_, &rsp_);
+
+    ASSERT_EQ(KM_ERROR_INVALID_DSA_PARAMS, rsp_.error);
+}
+
 TEST_F(NewKeyGeneration, Ecdsa) {
     req_.key_description.push_back(Authorization(TAG_ALGORITHM, KM_ALGORITHM_ECDSA));
     req_.key_description.push_back(Authorization(TAG_KEY_SIZE, 224));
@@ -505,6 +577,12 @@
     SignMessage(message, array_size(message) - 1);
 }
 
+TEST_F(SigningOperationsTest, DsaSuccess) {
+    GenerateKey(KM_ALGORITHM_DSA, KM_DIGEST_NONE, KM_PAD_NONE, 256 /* key size */);
+    const char message[] = "123456789012345678901234567890123456789012345678";
+    SignMessage(message, array_size(message) - 1);
+}
+
 TEST_F(SigningOperationsTest, EcdsaSuccess) {
     GenerateKey(KM_ALGORITHM_ECDSA, KM_DIGEST_NONE, KM_PAD_NONE, 224 /* key size */);
     const char message[] = "123456789012345678901234567890123456789012345678";
@@ -672,6 +750,13 @@
     VerifyMessage(message, array_size(message) - 1);
 }
 
+TEST_F(VerificationOperationsTest, DsaSuccess) {
+    GenerateKey(KM_ALGORITHM_DSA, KM_DIGEST_NONE, KM_PAD_NONE, 256 /* key size */);
+    const char message[] = "123456789012345678901234567890123456789012345678";
+    SignMessage(message, array_size(message) - 1);
+    VerifyMessage(message, array_size(message) - 1);
+}
+
 TEST_F(VerificationOperationsTest, EcdsaSuccess) {
     GenerateKey(KM_ALGORITHM_ECDSA, KM_DIGEST_NONE, KM_PAD_NONE, 224 /* key size */);
     const char message[] = "123456789012345678901234567890123456789012345678";
@@ -696,6 +781,22 @@
     // TODO(swillden): Verify that the exported key is actually usable to verify signatures.
 }
 
+TEST_F(ExportKeyTest, DsaSuccess) {
+    GenerateKey(KM_ALGORITHM_DSA, KM_DIGEST_NONE, KM_PAD_NONE, 1024 /* key size */);
+
+    ExportKeyRequest request;
+    ExportKeyResponse response;
+    AddClientParams(&request.additional_params);
+    request.key_format = KM_KEY_FORMAT_X509;
+    request.SetKeyMaterial(key_blob());
+
+    device.ExportKey(request, &response);
+    ASSERT_EQ(KM_ERROR_OK, response.error);
+    EXPECT_TRUE(response.key_data != NULL);
+
+    // TODO(swillden): Verify that the exported key is actually usable to verify signatures.
+}
+
 TEST_F(ExportKeyTest, EcdsaSuccess) {
     GenerateKey(KM_ALGORITHM_ECDSA, KM_DIGEST_NONE, KM_PAD_NONE, 224 /* key size */);
 
@@ -833,6 +934,136 @@
     ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH, import_response.error);
 }
 
+TEST_F(ImportKeyTest, DsaSuccess) {
+    keymaster_key_param_t params[] = {
+        Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN), Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY),
+        Authorization(TAG_DIGEST, KM_DIGEST_NONE), Authorization(TAG_PADDING, KM_PAD_NONE),
+        Authorization(TAG_USER_ID, 7), Authorization(TAG_USER_AUTH_ID, 8),
+        Authorization(TAG_APPLICATION_ID, "app_id", 6), Authorization(TAG_AUTH_TIMEOUT, 300),
+    };
+
+    string pk8_key = read_file("dsa_privkey_pk8.der");
+    ASSERT_EQ(335U, pk8_key.size());
+
+    ImportKeyRequest import_request;
+    import_request.key_description.Reinitialize(params, array_length(params));
+    import_request.key_format = KM_KEY_FORMAT_PKCS8;
+    import_request.SetKeyMaterial(pk8_key.data(), pk8_key.size());
+
+    ImportKeyResponse import_response;
+    device.ImportKey(import_request, &import_response);
+    ASSERT_EQ(KM_ERROR_OK, import_response.error);
+    EXPECT_EQ(0U, import_response.enforced.size());
+    EXPECT_GT(import_response.unenforced.size(), 0U);
+
+    // Check values derived from the key.
+    EXPECT_TRUE(contains(import_response.unenforced, TAG_ALGORITHM, KM_ALGORITHM_DSA));
+    EXPECT_TRUE(contains(import_response.unenforced, TAG_KEY_SIZE, 1024));
+
+    // And values provided by GoogleKeymaster
+    EXPECT_TRUE(contains(import_response.unenforced, TAG_ORIGIN, KM_ORIGIN_IMPORTED));
+    EXPECT_TRUE(contains(import_response.unenforced, KM_TAG_CREATION_DATETIME));
+
+    size_t message_len = 48;
+    UniquePtr<uint8_t[]> message(new uint8_t[message_len]);
+    std::fill(message.get(), message.get() + message_len, 'a');
+    SignMessage(import_response.key_blob, message.get(), message_len);
+    ASSERT_TRUE(signature() != NULL);
+    VerifyMessage(import_response.key_blob, message.get(), message_len);
+}
+
+TEST_F(ImportKeyTest, DsaParametersMatch) {
+    keymaster_key_param_t params[] = {
+        Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN), Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY),
+        Authorization(TAG_DIGEST, KM_DIGEST_NONE), Authorization(TAG_PADDING, KM_PAD_NONE),
+        Authorization(TAG_USER_ID, 7), Authorization(TAG_USER_AUTH_ID, 8),
+        Authorization(TAG_APPLICATION_ID, "app_id", 6), Authorization(TAG_AUTH_TIMEOUT, 300),
+        Authorization(TAG_KEY_SIZE, 1024),
+        Authorization(TAG_DSA_GENERATOR, dsa_g, array_size(dsa_g)),
+        Authorization(TAG_DSA_P, dsa_p, array_size(dsa_p)),
+        Authorization(TAG_DSA_Q, dsa_q, array_size(dsa_q)),
+    };
+
+    string pk8_key = read_file("dsa_privkey_pk8.der");
+    ASSERT_EQ(335U, pk8_key.size());
+
+    ImportKeyRequest import_request;
+    import_request.key_description.Reinitialize(params, array_length(params));
+    import_request.key_format = KM_KEY_FORMAT_PKCS8;
+    import_request.SetKeyMaterial(pk8_key.data(), pk8_key.size());
+
+    ImportKeyResponse import_response;
+    device.ImportKey(import_request, &import_response);
+    ASSERT_EQ(KM_ERROR_OK, import_response.error);
+    EXPECT_EQ(0U, import_response.enforced.size());
+    EXPECT_GT(import_response.unenforced.size(), 0U);
+
+    // Check values derived from the key.
+    EXPECT_TRUE(contains(import_response.unenforced, TAG_ALGORITHM, KM_ALGORITHM_DSA));
+    EXPECT_TRUE(contains(import_response.unenforced, TAG_KEY_SIZE, 1024));
+
+    // And values provided by GoogleKeymaster
+    EXPECT_TRUE(contains(import_response.unenforced, TAG_ORIGIN, KM_ORIGIN_IMPORTED));
+    EXPECT_TRUE(contains(import_response.unenforced, KM_TAG_CREATION_DATETIME));
+
+    size_t message_len = 48;
+    UniquePtr<uint8_t[]> message(new uint8_t[message_len]);
+    std::fill(message.get(), message.get() + message_len, 'a');
+    SignMessage(import_response.key_blob, message.get(), message_len);
+    ASSERT_TRUE(signature() != NULL);
+    VerifyMessage(import_response.key_blob, message.get(), message_len);
+}
+
+uint8_t dsa_wrong_q[] = {
+    0xC0, 0x66, 0x64, 0xF9, 0x05, 0x38, 0x64, 0x38, 0x4A, 0x17,
+    0x66, 0x79, 0xDD, 0x7F, 0x6E, 0x55, 0x22, 0x2A, 0xDF, 0xC5,
+};
+
+TEST_F(ImportKeyTest, DsaParameterMismatch) {
+    keymaster_key_param_t params[] = {
+        Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN), Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY),
+        Authorization(TAG_DIGEST, KM_DIGEST_NONE), Authorization(TAG_PADDING, KM_PAD_NONE),
+        Authorization(TAG_USER_ID, 7), Authorization(TAG_USER_AUTH_ID, 8),
+        Authorization(TAG_APPLICATION_ID, "app_id", 6), Authorization(TAG_AUTH_TIMEOUT, 300),
+        Authorization(TAG_KEY_SIZE, 1024),
+        Authorization(TAG_DSA_Q, dsa_wrong_q, array_size(dsa_wrong_q)),
+    };
+
+    string pk8_key = read_file("dsa_privkey_pk8.der");
+    ASSERT_EQ(335U, pk8_key.size());
+
+    ImportKeyRequest import_request;
+    import_request.key_description.Reinitialize(params, array_length(params));
+    import_request.key_format = KM_KEY_FORMAT_PKCS8;
+    import_request.SetKeyMaterial(pk8_key.data(), pk8_key.size());
+
+    ImportKeyResponse import_response;
+    device.ImportKey(import_request, &import_response);
+    ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH, import_response.error);
+}
+
+TEST_F(ImportKeyTest, DsaKeySizeMismatch) {
+    keymaster_key_param_t params[] = {
+        Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN), Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY),
+        Authorization(TAG_DIGEST, KM_DIGEST_NONE), Authorization(TAG_PADDING, KM_PAD_NONE),
+        Authorization(TAG_USER_ID, 7), Authorization(TAG_USER_AUTH_ID, 8),
+        Authorization(TAG_APPLICATION_ID, "app_id", 6), Authorization(TAG_AUTH_TIMEOUT, 300),
+        Authorization(TAG_KEY_SIZE, 2048),
+    };
+
+    string pk8_key = read_file("dsa_privkey_pk8.der");
+    ASSERT_EQ(335U, pk8_key.size());
+
+    ImportKeyRequest import_request;
+    import_request.key_description.Reinitialize(params, array_length(params));
+    import_request.key_format = KM_KEY_FORMAT_PKCS8;
+    import_request.SetKeyMaterial(pk8_key.data(), pk8_key.size());
+
+    ImportKeyResponse import_response;
+    device.ImportKey(import_request, &import_response);
+    ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH, import_response.error);
+}
+
 TEST_F(ImportKeyTest, EcdsaSuccess) {
     keymaster_key_param_t params[] = {
         Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN), Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY),
diff --git a/key.cpp b/key.cpp
index 975ce38..8ee0656 100644
--- a/key.cpp
+++ b/key.cpp
@@ -17,6 +17,7 @@
 #include <openssl/x509.h>
 
 #include "aes_key.h"
+#include "dsa_key.h"
 #include "ecdsa_key.h"
 #include "openssl_utils.h"
 #include "rsa_key.h"
@@ -41,6 +42,8 @@
     switch (blob.algorithm()) {
     case KM_ALGORITHM_RSA:
         return new RsaKey(blob, logger, error);
+    case KM_ALGORITHM_DSA:
+        return new DsaKey(blob, logger, error);
     case KM_ALGORITHM_ECDSA:
         return new EcdsaKey(blob, logger, error);
     default:
@@ -61,6 +64,8 @@
     switch (algorithm) {
     case KM_ALGORITHM_RSA:
         return RsaKey::GenerateKey(key_description, logger, error);
+    case KM_ALGORITHM_DSA:
+        return DsaKey::GenerateKey(key_description, logger, error);
     case KM_ALGORITHM_ECDSA:
         return EcdsaKey::GenerateKey(key_description, logger, error);
     case KM_ALGORITHM_AES:
@@ -104,6 +109,8 @@
     switch (EVP_PKEY_type(pkey->type)) {
     case EVP_PKEY_RSA:
         return RsaKey::ImportKey(key_description, pkey.get(), logger, error);
+    case EVP_PKEY_DSA:
+        return DsaKey::ImportKey(key_description, pkey.get(), logger, error);
     case EVP_PKEY_EC:
         return EcdsaKey::ImportKey(key_description, pkey.get(), logger, error);
     default: