iT邦幫忙

2024 iThome 鐵人賽

DAY 22
0
Software Development

Rust 學得動嗎系列 第 22

[Day 22] Rust 在密碼學和區塊鏈技術中的應用

  • 分享至 

  • xImage
  •  

今天,我們來聊聊 Rust 在密碼學和區塊鏈技術領域的應用。Rust 的安全性和高效能特性使其成為實現加密算法、數位簽名和區塊鏈結構的理想選擇,我們可以看到現在大部分的區塊鏈基本上是由Golang和Rust所開發出來的,使用Rust開發的區塊鏈有Solana,
Polkadot
Near等。

1. 使用 RustCrypto 進行加密操作

RustCrypto 是一系列密碼學相關的 Rust 套件集合。

AES 加密範例

use aes::Aes256;
use aes::cipher::{
    BlockCipher, BlockEncrypt, BlockDecrypt,
    generic_array::GenericArray,
};

fn main() {
    let key = GenericArray::from([0u8; 32]);
    let mut block = GenericArray::from([0u8; 16]);

    // 建立密碼
    let cipher = Aes256::new(&key);

    // 加密
    cipher.encrypt_block(&mut block);
    println!("加密後: {:?}", block);

    // 解密
    cipher.decrypt_block(&mut block);
    println!("解密後: {:?}", block);
}

2. 使用 ring 進行數位簽名

ring 是一個密碼學原語的集合,提供了高效率的實作。

use ring::{signature, rand};

fn main() {
    // 產生金鑰對
    let rng = rand::SystemRandom::new();
    let pkcs8_bytes = signature::Ed25519KeyPair::generate_pkcs8(&rng).unwrap();
    let key_pair = signature::Ed25519KeyPair::from_pkcs8(&pkcs8_bytes).unwrap();

    // 簽名
    let msg = b"Hello, World!";
    let sig = key_pair.sign(msg);

    // 驗證
    let public_key = key_pair.public_key();
    let verify_result = signature::UnparsedPublicKey::new(&signature::ED25519, public_key)
        .verify(msg, sig.as_ref());

    println!("驗證結果: {:?}", verify_result.is_ok());
}

3. 實作簡單的區塊鏈結構

使用 Rust 實作基本的區塊鏈結構。

use sha2::{Sha256, Digest};
use chrono::Utc;

struct Block {
    timestamp: i64,
    data: String,
    previous_hash: String,
    hash: String,
}

impl Block {
    fn new(data: String, previous_hash: String) -> Self {
        let timestamp = Utc::now().timestamp();
        let mut block = Block {
            timestamp,
            data,
            previous_hash,
            hash: String::new(),
        };
        block.hash = block.calculate_hash();
        block
    }

    fn calculate_hash(&self) -> String {
        let mut hasher = Sha256::new();
        hasher.update(self.timestamp.to_string());
        hasher.update(&self.data);
        hasher.update(&self.previous_hash);
        format!("{:x}", hasher.finalize())
    }
}

struct Blockchain {
    chain: Vec<Block>,
}

impl Blockchain {
    fn new() -> Self {
        let genesis_block = Block::new("創世區塊".to_string(), "0".to_string());
        Blockchain {
            chain: vec![genesis_block],
        }
    }

    fn add_block(&mut self, data: String) {
        let previous_hash = self.chain.last().unwrap().hash.clone();
        let new_block = Block::new(data, previous_hash);
        self.chain.push(new_block);
    }
}

fn main() {
    let mut blockchain = Blockchain::new();
    blockchain.add_block("交易 1".to_string());
    blockchain.add_block("交易 2".to_string());

    for (i, block) in blockchain.chain.iter().enumerate() {
        println!("區塊 {}", i);
        println!("時間戳: {}", block.timestamp);
        println!("資料: {}", block.data);
        println!("雜湊值: {}", block.hash);
        println!("前一個區塊雜湊值: {}", block.previous_hash);
        println!();
    }
}

4. 使用 secp256k1 進行橢圓曲線密碼學操作

secp256k1 是比特幣和以太坊使用的橢圓曲線演算法。

use secp256k1::{Secp256k1, Message, SecretKey, PublicKey};
use rand::rngs::OsRng;

fn main() {
    let secp = Secp256k1::new();
    let mut rng = OsRng::new().expect("OsRng");
    
    // 生成金鑰對
    let (secret_key, public_key) = secp.generate_keypair(&mut rng);

    // 訊息簽名
    let message = Message::from_slice(&[0xab; 32]).expect("32 bytes");
    let sig = secp.sign(&message, &secret_key);

    // 驗證簽名
    assert!(secp.verify(&message, &sig, &public_key).is_ok());

    println!("簽名驗證成功!");
}

5. 使用 sodiumoxide 進行通用加密操作

sodiumoxide 是 libsodium 的 Rust 綁定,提供了高階的密碼學原語。

use sodiumoxide::crypto::box_;

fn main() {
    sodiumoxide::init().unwrap();

    // 生成金鑰對
    let (public_key, secret_key) = box_::gen_keypair();

    // 加密訊息
    let nonce = box_::gen_nonce();
    let plaintext = b"Hello, World!";
    let ciphertext = box_::seal(plaintext, &nonce, &public_key, &secret_key);

    // 解密訊息
    let decrypted = box_::open(&ciphertext, &nonce, &public_key, &secret_key).unwrap();

    assert_eq!(&decrypted[..], &plaintext[..]);
    println!("加密和解密成功!");
}

結論

Rust 在密碼學和區塊鏈技術領域展現出了巨大的潛力。它的安全性保證和高效率特性使其成為實現加密算法、數位簽名和區塊鏈結構的理想選擇。Rust 的強大型別系統和記憶體安全特性有助於防止常見的密碼學實作錯誤,同時效能適合處理大規模的加密操作和區塊鏈交易,學習Rust可以在相關的區塊鏈上進行開發。


上一篇
[Day21] Rust 在遊戲開發中的應用
系列文
Rust 學得動嗎22
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言