Try   HackMD

基本密碼學 Encode, Encrypt, hash 差異

tags: IS
  • 知識背景
  • 編碼 Encode
  • 加密 Encrypt
  • 雜湊 hash
  • 綜合應用

編碼 Encode

換個方式來呈現資料,沒有任何安全性,主要看編碼後的用途 QRcode, UTF8. Base64 等等

QRcode 用圖像來呈現資料

Base64 不是加密,而是一種編碼演算法

// 編碼
$ echo Man | base64
$ TWFuCg==

// 解碼
$ echo TWFuCg== | base64 -d
$ Man

壓縮技術原理 就像 Huffman Coding 霍夫曼編碼一樣,建一棵樹做頻率分析

  • 越常出現的編碼越短

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →


加密 Encrypt

將明文資訊轉變成難以讀取的密文,需要一組 key 來進行加密編碼

Caesar Cipher 凱薩加密法,傳入偏移字母數

最多只有字母總數的加密數

AES 對稱加密演算法

加密解密同一組 key

// 加密
$ openssl aes-128-cbc -n text -out text_encrypted
$ enter aes-123-cbc encryption password:

// 解密
$ openssl aes-128-cbc -d -in text_encrypted -out text2
$ enter aes-123-cbc decryption password:

RSA 非對稱加密演算法

公鑰加密的內容只能用私鑰解 openssl aes encrypt and decrypt

[步驟]

  1. 產生公鑰與私鑰
  2. 私鑰解密者留著,並傳送公鑰給加密者
  3. 加密者用公鑰加密檔案後給解密者
  4. 解密者使用公鑰解密檔案
// 產生公私鑰
$ openssl genrsa -out private.pem
// 取出公鑰
$ openssl rsa -pubout -in private.pem -out public.pem

// encrypt with public key
$ openssl rsautl -encrypt -in <in_file> -out <out_file> -pubin -inkey public.pem

// decrypt with private key
$ openssl rsautl -decrypt -in <in_file> -out <out_file> -inkey private.pem

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →


雜湊 Hash

將資料內容打亂、混合 無法反推回原本內容 相同輸入會有 MD5, SHA, bcrypt

身分證

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

md5

$ md5 <file>

SHA384 (Sercure Hash Algorithm)

256 / 384 / 512

$ shasum -a 256 <file>
$ echo password1234 | shasum -a 384

Boostrapt link 範例 裡面有 integrity 只要下載下來的檔案與加密碼不相同就不會被下載下來

<!-- Bootstrap CSS -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous">

如果下載的檔案沒有 integrity 可以自行下載下來加密

// 下載
$ wget <https://XXX>

// 加密
$ shasum -a 512 <file>

綜合應用

  • 壓縮檔加密: 編碼+加密
  • HTTPS:RSA + AES
  • 數位簽章:雜湊 + RSA
  • JWT(Json Web Token):雜湊 + 編碼