密钥对的主要功能是签署消息、交易并启用签名验证。签名验证可让接收者确信数据是由特定私钥的所有者签名的。
Kit
import {
generateKeyPair,
signBytes,
verifySignature,
getUtf8Encoder,
getBase58Decoder,
} from "@solana/kit";
const keys = await generateKeyPair();
const message = getUtf8Encoder().encode("Hello, World!");
const signedBytes = await signBytes(keys.privateKey, message);
const decoded = getBase58Decoder().decode(signedBytes);
console.log("Signature:", decoded);
const verified = await verifySignature(keys.publicKey, signedBytes, message);
console.log("Verified:", verified);
Web3.js
// In Solana Web3.js v1, we can use the TweetNaCl crypto library:
import { Keypair } from "@solana/web3.js";
import nacl from "tweetnacl";
import nacl_util from "tweetnacl-util";
const keypair = Keypair.fromSecretKey(
Uint8Array.from([
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56,
222, 53, 138, 189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246,
15, 185, 186, 82, 177, 240, 148, 69, 241, 227, 167, 80, 141, 89, 240, 121,
121, 35, 172, 247, 68, 251, 226, 218, 48, 63, 176, 109, 168, 89, 238, 135,
]),
);
const message = "The quick brown fox jumps over the lazy dog";
const messageBytes = nacl_util.decodeUTF8(message);
const signature = nacl.sign.detached(messageBytes, keypair.secretKey);
const result = nacl.sign.detached.verify(
messageBytes,
signature,
keypair.publicKey.toBytes(),
);
console.log(result);
Rust
use anyhow::Result;
use solana_sdk::{signature::Keypair, signer::Signer};
fn main() -> Result<()> {
let keypair_bytes = [
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56, 222, 53, 138,
189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246, 15, 185, 186, 82, 177, 240,
148, 69, 241, 227, 167, 80, 141, 89, 240, 121, 121, 35, 172, 247, 68, 251, 226, 218, 48,
63, 176, 109, 168, 89, 238, 135,
];
let keypair = Keypair::from_bytes(&keypair_bytes)?;
let message = "The quick brown fox jumps over the lazy dog";
let signature = keypair.sign_message(message.as_bytes());
let is_valid_signature = signature.verify(&keypair.pubkey().to_bytes(), message.as_bytes());
println!("is valid signature: {:?}", is_valid_signature);
Ok(())
}
https://solana.com/zh/developers/cookbook/wallets/sign-message
版权属于:区块链中文技术社区 / 转载原创者
本文链接:https://www.bcskill.com/index.php/archives/2287.html
相关技术文章仅限于相关区块链底层技术研究,禁止用于非法用途,后果自负!本站严格遵守一切相关法律政策!
楼主残忍的关闭了评论