iT邦幫忙

2024 iThome 鐵人賽

DAY 14
0

使用 jose-swift 實現 JWE 加密和解密

在這篇文章中,我們將展示如何使用 jose-swift 套件來實現 JWE (JSON Web Encryption) 加密和解密。這邊先附上全部的程式碼後再來跟各位介紹。

import jose_swift

let encryptPrivateKey = P384.KeyAgreement.PrivateKey()

let payload = "Hello world".data(using: .utf8)!
do {
    let jwe = try JWE(payload: payload,
                      keyManagementAlg: .ecdhES,
                      encryptionAlgorithm: .a256GCM,
                      recipientKey: encryptPrivateKey.publicKey)

    let decrypted = try jwe.decrypt(recipientKey: encryptPrivateKey)
    
    print(String(data: decrypted, encoding: .utf8)!)
} catch {
    print(error)
}

首先我們先創建一把privateKey ,是使用 CryptoKit 這個套件裡面的 P384 生成的
然後我們將要加密的字串轉換成 Data 的型態

什麼是 keyManagementAlg、encryptionAlgorithm、recipientKey

  1. keyManagementAlg

    keyManagementAlg 是指鍵管理算法,它決定了如何管理和分發加密密鑰。在我們的例子中,我們使用的是 .ecdhES 算法,即 EC Diffie-Hellman Ephemeral Static。這種算法使用一對公開和私有密鑰來生成一個共享的秘密密鑰,用於對稱加密。

   let keyManagementAlg: KeyManagementAlgorithm = .ecdhES
  1. encryptionAlgorithm
    encryptionAlgorithm 是指加密算法,它決定了如何實際加密數據(負載)。在我們的例子中,我們使用的是 .a256GCM 算法,即 AES-256-GCM(Advanced Encryption Standard with 256-bit key in Galois/Counter Mode)。這是一種高安全性的對稱加密算法。
    let encryptionAlg: ContentEncryptionAlgorithm = .a256GCM
  1. recipientKey
    recipientKey(公鑰) 這是接收方提供的公鑰,用於加密資料。這個公鑰與接收方的私鑰配對,用於確保只有擁有相應私鑰的接收方能夠解密該資料。
    let recipientKey = encryptPrivateKey.publicKey

Decrypt JWE

最後是解密的部分,我們會需要使用到 recipientKey 這個參數,這邊我們有兩個解密方法

  1. 透過剛剛創好的 PrivateKey
    let decrypted = try jwe.decrypt(recipientKey: encryptPrivateKey)
  1. 透過剛剛創好的 PrivateKey 的 JWK
    let decrypted = try jwe.decrypt(recipientKey: encryptPrivateKey.jwk)

最後就可以得到我們一開始的 Hello World 囉


上一篇
Day13 - 什麼是 JOSE
下一篇
Day15 - 實作 JWE 加解密(2)
系列文
Xiang教你進階Swift從有到精19
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言