はじめに
Viem で AWS Key Management Service(AWS KMS)を利用し、Ethereum の署名に使える Account を作成します。
Viem には privateKeyToAccount、mnemonicToAccount、hdKeyToAccount が用意されていますが、AWS KMS の鍵をそのまま扱う関数はありません。
そこで今回は awskmsToAccount を実装し、Viem から LocalAccount として扱えるようにします。
前提条件
実装に入る前に、AWS KMS 側で押さえる点があります。
- KMS の鍵種別は secp256k1 を使う
- AWS KMS では
ECC_SECG_P256K1の鍵が必要です
- AWS KMS では
- 署名アルゴリズムは
ECDSA_SHA_256を使う - 必要な権限は最低でも
kms:GetPublicKeyとkms:Sign
アカウント
ここでは、awskmsToAccount を作成し、LocalAccount を返します。
以下がソースコードです。
export async function awskmsToAccount(
keyId: string,
config?: KMSClientConfig,
nonceManager?: NonceManager,
): Promise<LocalAccount<string>> {
// KMSクライアントを作成します。
const kmsClient = new KMSClient(config || {});
// キーIDに対応する公開鍵を取得します。
const command = new GetPublicKeyCommand({ KeyId: keyId });
const response = await kmsClient.send(command);
const publicKey = response.PublicKey;
if (!publicKey) {
throw new Error("Failed to retrieve public key from AWS KMS");
}
const ecPublicKey = AsnConvert.parse(
Buffer.from(publicKey),
SubjectPublicKeyInfo,
).subjectPublicKey;
// 公開鍵から Ethereum アドレスを導出します。
const address = publicKeyToAddress(bytesToHex(new Uint8Array(ecPublicKey)));
// LocalAccount オブジェクトを作成して返します。
const account: LocalAccount<string> = {
address: address,
nonceManager: nonceManager,
async sign({ hash }) {
return await _sign({ kmsClient, keyId, address, hash, to: "hex" });
},
async signAuthorization(authorization) {
return _signAuthorization(
kmsClient,
keyId,
address,
authorization as SignAuthorizationParameters<"object">,
);
},
async signMessage({ message }) {
return _signMessage(kmsClient, keyId, address, message);
},
async signTransaction(transaction, options?) {
return _signTransaction(kmsClient, keyId, address, transaction, options);
},
async signTypedData(typedData) {
return _signTypedData(kmsClient, keyId, address, typedData);
},
publicKey: bytesToHex(new Uint8Array(ecPublicKey)),
source: "aws-kms",
type: "local",
};
return account;
}
重要なのは、AWS KMS の GetPublicKey が Ethereum でそのまま使える公開鍵を返すわけではない点です。
SubjectPublicKeyInfo を ASN.1 としてパースし、中の EC 公開鍵を取り出した上で publicKeyToAddress に渡しています。
また、LocalAccount として返しているので、Viem の walletClient など既存の API にそのまま渡せます。
単に署名関数を作るのではなく、Viem のアカウントインターフェースへ合わせているのがポイントです。
sign
署名は AWS KMS を使用した実装です。
_sign はアカウントの sign だけではなく他の署名でも使用するため、戻り値の型は SignReturnType にしています。
const N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;
const HALF_N = N >> 1n;
type To = "object" | "bytes" | "hex";
type AwsKmsSignParameters<to extends To = "object"> = {
kmsClient: KMSClient;
keyId: string;
address: Address;
hash: Hash;
to?: to | To | undefined;
};
async function _sign<to extends To = "object">({
kmsClient,
keyId,
address,
hash,
to = "object",
}: AwsKmsSignParameters<to>): Promise<SignReturnType<to>> {
// Create the SignCommand with the appropriate parameters for AWS KMS
const command = new SignCommand({
KeyId: keyId,
Message: hexToBytes(hash),
SigningAlgorithm: "ECDSA_SHA_256",
MessageType: "DIGEST",
});
// Retrieve the signature from AWS KMS
const response = await kmsClient.send(command);
const awsKmsSignature = response.Signature;
// If the signature is not available, throw an error
if (!awsKmsSignature) {
throw new Error("Failed to sign message with AWS KMS");
}
// Parse the signature from ASN.1 format to extract the r and s values
const ecdsaSig = AsnConvert.parse(Buffer.from(awsKmsSignature), ECDSASigValue);
// Handle low S values by ensuring that s is less than or equal to N/2.
// If s is greater than N/2, it is replaced with N - s to ensure that the signature is in canonical form, which is required by Ethereum.
// https://ethereum.github.io/yellowpaper/paper.pdf - Appendix F. Signing Transactions
let s = bytesToBigInt(new Uint8Array(ecdsaSig.s));
if (s > HALF_N) {
s = N - s;
}
// Construct the signature in the format expected by Ethereum (r, s, v)
const signature = {
r: numberToHex(bytesToBigInt(new Uint8Array(ecdsaSig.r)), { size: 32 }),
s: numberToHex(s, { size: 32 }),
v: 27n,
yParity: 0,
};
// Verify the signature to determine the correct v value (27 or 28) and yParity
const verify = await verifyHash({ hash, address, signature });
// If the signature is not valid, it may be due to the v value being incorrect.
if (!verify) {
signature.v = 28n;
signature.yParity = 1;
}
return (() => {
if (to === "bytes" || to === "hex") return serializeSignature({ ...signature, to });
return signature;
})() as SignReturnType<to>;
}
この関数で特に重要なのは 3 点です。
まず、KMS に渡しているのは生のメッセージではなくハッシュ済みの値です。
そのため MessageType: "DIGEST" を指定しています。
signMessage、signTypedData、signTransaction はそれぞれ Ethereum の仕様に沿ってハッシュ化したあと、この _sign に処理を集約しています。
次に、KMS が返す署名は ASN.1 DER 形式です。
Ethereum が期待するのは r s v の形式なので、ECDSASigValue としてパースしてから組み直しています。
最後に、AWS KMS は recovery id を返さないため、v を固定では決められません。
ここでは verifyHash を使って v = 27 と v = 28 のどちらが正しいかを判定しています。
signAuthorization
EIP-7702で使用する署名です。
/**
* Signs an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.
*/
export async function _signAuthorization<to extends To = "object">(
kmsClient: KMSClient,
keyId: string,
address: Address,
parameters: SignAuthorizationParameters<to>,
): Promise<SignAuthorizationReturnType<to>> {
const { chainId, nonce, to = "object" } = parameters;
const address_ = parameters.contractAddress ?? parameters.address;
const signature = await _sign({
kmsClient,
keyId,
address,
hash: hashAuthorization({ address: address_, chainId, nonce }),
to,
});
if (to === "object")
return {
address: address_,
chainId,
nonce,
...(signature as Signature),
} as unknown as SignAuthorizationReturnType<to>;
return signature as unknown as SignAuthorizationReturnType<to>;
}
object(デフォルト)で返す場合、address、chainId、nonce を付与して返しています。
signMessage
EIP-191 で規定されている署名です。
/**
* @description Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):
* `keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))`.
*
* @returns The signature.
*/
export async function _signMessage(
kmsClient: KMSClient,
keyId: string,
address: Address,
message: SignableMessage,
): Promise<Hex> {
return await _sign({
kmsClient,
keyId,
address,
hash: hashMessage(message),
to: "hex",
});
}
重要なのは、文字列を hashMessage で EIP-191 の形式に従ってハッシュ化してから _sign に渡しています。
signTransaction
トランザクションを署名して、署名付きのトランザクションを返します。
export async function _signTransaction<
serializer extends SerializeTransactionFn<TransactionSerializable> =
SerializeTransactionFn<TransactionSerializable>,
transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],
>(
kmsClient: KMSClient,
keyId: string,
address: Address,
transaction: transaction,
options?:
| {
serializer?: serializer | undefined;
}
| undefined,
): Promise<Hex> {
const { serializer = serializeTransaction } = options || {};
const signableTransaction = (() => {
// For EIP-4844 Transactions, we want to sign the transaction payload body (tx_payload_body) without the sidecars (ie. without the network wrapper).
// See: https://github.com/ethereum/EIPs/blob/e00f4daa66bd56e2dbd5f1d36d09fd613811a48b/EIPS/eip-4844.md#networking
if (transaction.type === "eip4844")
return {
...transaction,
sidecars: false,
};
return transaction;
})();
const signature = await _sign({
kmsClient,
keyId,
address,
hash: keccak256(await serializer(signableTransaction)),
});
return (await serializer(transaction, signature)) as Hex;
}
トランザクション署名では、まず署名対象のトランザクションをシリアライズし、そのハッシュを _sign に渡します。
最後に得られた署名を元のトランザクションへ埋め込み、署名済みトランザクションとして返します。
signTypedData
EIP-712で規定されている署名です。
/**
* @description Signs typed data and calculates an Ethereum-specific signature in [https://eips.ethereum.org/EIPS/eip-712](https://eips.ethereum.org/EIPS/eip-712):
* `sign(keccak256("\x19\x01" ‖ domainSeparator ‖ hashStruct(message)))`.
*
* @returns The signature.
*/
export async function _signTypedData<
const typedData extends TypedData | Record<string, unknown>,
primaryType extends keyof typedData | "EIP712Domain" = keyof typedData,
>(
kmsClient: KMSClient,
keyId: string,
address: Address,
parameters: TypedDataDefinition<typedData, primaryType>,
): Promise<Hex> {
const { ...typedData } = parameters as unknown as SignTypedDataParameters;
return await _sign({
kmsClient,
keyId,
address,
hash: hashTypedData(typedData),
to: "hex",
});
}
ここも考え方は同じで、EIP-712 に従って typed data をハッシュ化し、その結果だけを KMS に渡しています。
まとめ
AWS KMS を使っても、公開鍵の取り出しと署名形式の変換をきちんと行えば、Viem の LocalAccount として扱えます。
実装で重要だったのは次の点です。
- 公開鍵の ASN.1 変換
- 署名の ASN.1 DER 変換
- low-s への正規化
-
v/yParityの補完 - EIP-191、EIP-712、EIP-7702、Transaction ごとの適切なハッシュ化
さまざまな場所からコードを確認する必要があったので、作成には少し手間がかかりました。
sign だけ差し替えれば済むようなインターフェースだと、他の KMS や HSM にも横展開しやすいので、そういった拡張ポイントがあるとより扱いやすいと感じました。
Appendix
コード
コード(1ファイル)
import {
publicKeyToAddress,
SignAuthorizationReturnType,
SignAuthorizationParameters,
SignReturnType,
} from "viem/accounts";
import { hashAuthorization } from "viem/utils";
import {
bytesToHex,
hexToBytes,
bytesToBigInt,
numberToHex,
serializeTransaction,
Address,
NonceManager,
serializeSignature,
verifyHash,
hashMessage,
keccak256,
Signature,
hashTypedData,
Hex,
Hash,
SignableMessage,
SerializeTransactionFn,
TransactionSerializable,
SignTypedDataParameters,
TypedData,
TypedDataDefinition,
LocalAccount,
} from "viem";
import { KMSClient, KMSClientConfig, GetPublicKeyCommand, SignCommand } from "@aws-sdk/client-kms";
import { ECDSASigValue } from "@peculiar/asn1-ecc";
import { AsnConvert } from "@peculiar/asn1-schema";
import { SubjectPublicKeyInfo } from "@peculiar/asn1-x509";
export async function awskmsToAccount(
keyId: string,
config?: KMSClientConfig,
nonceManager?: NonceManager,
): Promise<LocalAccount<string>> {
// KMSクライアントを作成します。
const kmsClient = new KMSClient(config || {});
// キーIDに対応する公開鍵を取得します。
const command = new GetPublicKeyCommand({ KeyId: keyId });
const response = await kmsClient.send(command);
const publicKey = response.PublicKey;
if (!publicKey) {
throw new Error("Failed to retrieve public key from AWS KMS");
}
const ecPublicKey = AsnConvert.parse(
Buffer.from(publicKey),
SubjectPublicKeyInfo,
).subjectPublicKey;
// 公開鍵から Ethereum アドレスを導出します。
const address = publicKeyToAddress(bytesToHex(new Uint8Array(ecPublicKey)));
// LocalAccount オブジェクトを作成して返します。
const account: LocalAccount<string> = {
address: address,
nonceManager: nonceManager,
async sign({ hash }) {
return await _sign({ kmsClient, keyId, address, hash, to: "hex" });
},
async signAuthorization(authorization) {
return _signAuthorization(
kmsClient,
keyId,
address,
authorization as SignAuthorizationParameters<"object">,
);
},
async signMessage({ message }) {
return _signMessage(kmsClient, keyId, address, message);
},
async signTransaction(transaction, options?) {
return _signTransaction(kmsClient, keyId, address, transaction, options);
},
async signTypedData(typedData) {
return _signTypedData(kmsClient, keyId, address, typedData);
},
publicKey: bytesToHex(new Uint8Array(ecPublicKey)),
source: "aws-kms",
type: "local",
};
return account;
}
const N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;
const HALF_N = N >> 1n;
type To = "object" | "bytes" | "hex";
type AwsKmsSignParameters<to extends To = "object"> = {
kmsClient: KMSClient;
keyId: string;
address: Address;
hash: Hash;
to?: to | To | undefined;
};
async function _sign<to extends To = "object">({
kmsClient,
keyId,
address,
hash,
to = "object",
}: AwsKmsSignParameters<to>): Promise<SignReturnType<to>> {
// Create the SignCommand with the appropriate parameters for AWS KMS
const command = new SignCommand({
KeyId: keyId,
Message: hexToBytes(hash),
SigningAlgorithm: "ECDSA_SHA_256",
MessageType: "DIGEST",
});
// Retrieve the signature from AWS KMS
const response = await kmsClient.send(command);
const awsKmsSignature = response.Signature;
// If the signature is not available, throw an error
if (!awsKmsSignature) {
throw new Error("Failed to sign message with AWS KMS");
}
// Parse the signature from ASN.1 format to extract the r and s values
const ecdsaSig = AsnConvert.parse(Buffer.from(awsKmsSignature), ECDSASigValue);
// Handle low S values by ensuring that s is less than or equal to N/2.
// If s is greater than N/2, it is replaced with N - s to ensure that the signature is in canonical form, which is required by Ethereum.
// https://ethereum.github.io/yellowpaper/paper.pdf - Appendix F. Signing Transactions
let s = bytesToBigInt(new Uint8Array(ecdsaSig.s));
if (s > HALF_N) {
s = N - s;
}
// Construct the signature in the format expected by Ethereum (r, s, v)
const signature = {
r: numberToHex(bytesToBigInt(new Uint8Array(ecdsaSig.r)), { size: 32 }),
s: numberToHex(s, { size: 32 }),
v: 27n,
yParity: 0,
};
// Verify the signature to determine the correct v value (27 or 28) and yParity
const verify = await verifyHash({ hash, address, signature });
// If the signature is not valid, it may be due to the v value being incorrect.
if (!verify) {
signature.v = 28n;
signature.yParity = 1;
}
return (() => {
if (to === "bytes" || to === "hex") return serializeSignature({ ...signature, to });
return signature;
})() as SignReturnType<to>;
}
/**
* Signs an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.
*/
export async function _signAuthorization<to extends To = "object">(
kmsClient: KMSClient,
keyId: string,
address: Address,
parameters: SignAuthorizationParameters<to>,
): Promise<SignAuthorizationReturnType<to>> {
const { chainId, nonce, to = "object" } = parameters;
const address_ = parameters.contractAddress ?? parameters.address;
const signature = await _sign({
kmsClient,
keyId,
address,
hash: hashAuthorization({ address: address_, chainId, nonce }),
to,
});
if (to === "object")
return {
address: address_,
chainId,
nonce,
...(signature as Signature),
} as unknown as SignAuthorizationReturnType<to>;
return signature as unknown as SignAuthorizationReturnType<to>;
}
/**
* @description Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):
* `keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))`.
*
* @returns The signature.
*/
export async function _signMessage(
kmsClient: KMSClient,
keyId: string,
address: Address,
message: SignableMessage,
): Promise<Hex> {
return await _sign({
kmsClient,
keyId,
address,
hash: hashMessage(message),
to: "hex",
});
}
export async function _signTransaction<
serializer extends SerializeTransactionFn<TransactionSerializable> =
SerializeTransactionFn<TransactionSerializable>,
transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],
>(
kmsClient: KMSClient,
keyId: string,
address: Address,
transaction: transaction,
options?:
| {
serializer?: serializer | undefined;
}
| undefined,
): Promise<Hex> {
const { serializer = serializeTransaction } = options || {};
const signableTransaction = (() => {
// For EIP-4844 Transactions, we want to sign the transaction payload body (tx_payload_body) without the sidecars (ie. without the network wrapper).
// See: https://github.com/ethereum/EIPs/blob/e00f4daa66bd56e2dbd5f1d36d09fd613811a48b/EIPS/eip-4844.md#networking
if (transaction.type === "eip4844")
return {
...transaction,
sidecars: false,
};
return transaction;
})();
const signature = await _sign({
kmsClient,
keyId,
address,
hash: keccak256(await serializer(signableTransaction)),
});
return (await serializer(transaction, signature)) as Hex;
}
/**
* @description Signs typed data and calculates an Ethereum-specific signature in [https://eips.ethereum.org/EIPS/eip-712](https://eips.ethereum.org/EIPS/eip-712):
* `sign(keccak256("\x19\x01" ‖ domainSeparator ‖ hashStruct(message)))`.
*
* @returns The signature.
*/
export async function _signTypedData<
const typedData extends TypedData | Record<string, unknown>,
primaryType extends keyof typedData | "EIP712Domain" = keyof typedData,
>(
kmsClient: KMSClient,
keyId: string,
address: Address,
parameters: TypedDataDefinition<typedData, primaryType>,
): Promise<Hex> {
const { ...typedData } = parameters as unknown as SignTypedDataParameters;
return await _sign({
kmsClient,
keyId,
address,
hash: hashTypedData(typedData),
to: "hex",
});
}