 +	int			data_len,
 +				res;
 +	char	   *buf;
-+	char	   *key,
++	text	   *key,
 +			   *utf8key;
 +	int			buflen;
 +
 +	data = PG_GETARG_BYTEA_P(0);
 +	data_len = VARSIZE(data) - VARHDRSZ;
 +
-+	/* convert the key to UTF-8 */
-+	key = text_to_cstring(PG_GETARG_TEXT_PP(1));
-+	utf8key = pg_server_to_any(key, strlen(key), PG_UTF8);
-+
++	key = PG_GETARG_TEXT_P(1);
++	utf8key = convert_to_utf8(key);
 +	res = pgp_armor_header((uint8 *) VARDATA(data), data_len,
-+							utf8key, strlen(utf8key),
++							VARDATA(utf8key), VARSIZE(utf8key) - VARHDRSZ,
 +							(uint8 **) &buf, &buflen);
 +	if (res < 0)
 +		ereport(ERROR,

 	if (res_len > guess_len)
 		ereport(ERROR,
 				(errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION),
@@ -890,6 +968,52 @@ pg_dearmor(PG_FUNCTION_ARGS)
 	PG_RETURN_TEXT_P(res);
 }
 

+	PG_FREE_IF_COPY(data, 0);
+	if (utf8key != key)
+		pfree(utf8key);
+	PG_FREE_IF_COPY(key, 1);
+	if (!buf)
+		PG_RETURN_NULL();
+	else
