+#include "internal/cryptlib.h"
+#include <openssl/asn1t.h>
+#include <openssl/x509.h>
+#include "internal/asn1_int.h"
+#include "internal/evp_int.h"
+#ifndef OPENSSL_NO_RSA
+# include <openssl/rsa.h>
+#endif
+#ifndef OPENSSL_NO_DSA
+# include <openssl/dsa.h>
+#endif
+
+/* Minor tweak to operation: free up EVP_PKEY */
+static int pubkey_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
+ void *exarg)
+{
+ if (operation == ASN1_OP_NEW_POST) {
+ X509_PUBKEY *pubkey = (X509_PUBKEY *)*pval;
+ pubkey->lock = CRYPTO_THREAD_lock_new();
+ if (pubkey->lock == NULL)
+ return 0;
+ }
+ if (operation == ASN1_OP_FREE_POST) {
+ X509_PUBKEY *pubkey = (X509_PUBKEY *)*pval;
+ CRYPTO_THREAD_lock_free(pubkey->lock);
+ EVP_PKEY_free(pubkey->pkey);
+ }
+ return 1;
+}
+
+ASN1_SEQUENCE_cb(X509_PUBKEY, pubkey_cb) = {
+ ASN1_SIMPLE(X509_PUBKEY, algor, X509_ALGOR),
+ ASN1_SIMPLE(X509_PUBKEY, public_key, ASN1_BIT_STRING)
+} ASN1_SEQUENCE_END_cb(X509_PUBKEY, X509_PUBKEY)
+
+IMPLEMENT_ASN1_FUNCTIONS(X509_PUBKEY)
+
+int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey)
+{
+ X509_PUBKEY *pk = NULL;
+
+ if (x == NULL)
+ return (0);
+
+ if ((pk = X509_PUBKEY_new()) == NULL)
+ goto error;
+
+ if (pkey->ameth) {
+ if (pkey->ameth->pub_encode) {
+ if (!pkey->ameth->pub_encode(pk, pkey)) {
+ X509err(X509_F_X509_PUBKEY_SET,
+ X509_R_PUBLIC_KEY_ENCODE_ERROR);
+ goto error;
+ }
+ } else {
+ X509err(X509_F_X509_PUBKEY_SET, X509_R_METHOD_NOT_SUPPORTED);
+ goto error;
+ }
+ } else {
+ X509err(X509_F_X509_PUBKEY_SET, X509_R_UNSUPPORTED_ALGORITHM);
+ goto error;
+ }
+
+ X509_PUBKEY_free(*x);
+ *x = pk;
+ return 1;
+
+ error:
+ X509_PUBKEY_free(pk);
+ return 0;
+}
+
+EVP_PKEY *X509_PUBKEY_get0(X509_PUBKEY *key)
+{
+ EVP_PKEY *ret = NULL;
+
+ if (key == NULL)
+ goto error;
+
+ if (key->pkey != NULL)
+ return key->pkey;
+
+ if (key->public_key == NULL)
+ goto error;
+
+ if ((ret = EVP_PKEY_new()) == NULL) {
+ X509err(X509_F_X509_PUBKEY_GET0, ERR_R_MALLOC_FAILURE);
+ goto error;
+ }
+
+ if (!EVP_PKEY_set_type(ret, OBJ_obj2nid(key->algor->algorithm))) {
+ X509err(X509_F_X509_PUBKEY_GET0, X509_R_UNSUPPORTED_ALGORITHM);
+ goto error;
+ }
+
+ if (ret->ameth->pub_decode) {
+ if (!ret->ameth->pub_decode(ret, key)) {
+ X509err(X509_F_X509_PUBKEY_GET0, X509_R_PUBLIC_KEY_DECODE_ERROR);
+ goto error;
+ }
+ } else {
+ X509err(X509_F_X509_PUBKEY_GET0, X509_R_METHOD_NOT_SUPPORTED);
+ goto error;
+ }
+
+ /* Check to see if another thread set key->pkey first */
+ CRYPTO_THREAD_write_lock(key->lock);
+ if (key->pkey) {
+ CRYPTO_THREAD_unlock(key->lock);
+ EVP_PKEY_free(ret);
+ ret = key->pkey;
+ } else {
+ key->pkey = ret;
+ CRYPTO_THREAD_unlock(key->lock);
+ }
+
+ return ret;
+
+ error:
+ EVP_PKEY_free(ret);
+ return (NULL);
+}
+
+EVP_PKEY *X509_PUBKEY_get(X509_PUBKEY *key)
+{
+ EVP_PKEY *ret = X509_PUBKEY_get0(key);
+ if (ret != NULL)
+ EVP_PKEY_up_ref(ret);
+ return ret;
+}