samson_chaechae
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # RC4加密算法(學習筆記) ## 簡介 RC4是一種串流加密法,密鑰長度可變。其屬於對稱式加密,且加解密過程一樣。 ## 原理 ### 初始化 1. 初始化S盒,其中包含所有0到255的元素(S[i] = i) 2. KSA——用一個密鑰進行一系列操作交換S盒,以根據密鑰混淆S盒。(因為不難,且code比中文好理解,故不詳述) 注:密鑰可以為任意長度,RC4會重複使用,直到將長度擴展到256字節 ### 加密 1. 偽隨機算法PRGA(i,j從零開始,重複以下動作len(plaintext)次) - i = (i + 1) mod 256 - j = (j + S[i]) mod 256 - 交換S[i]和S[j]的值。 - 根據交換後的S,計算k = (S[i] + S[j]) mod 256。 - 選擇S[k]作為密鑰流的下一個位元組。 2. 密文=明文xor由S[k]組成的密鑰流 ## 解密 由於使用一樣的密鑰經過KSA和PRGA後會完全得到一樣的S盒和一樣的密鑰流 且A xor B xor B = A 故加密和解密的過程完全一樣 ## 安全性 1. 由於RC4生成的密鑰流可以不斷延長的,所以每段明文都是由不同的部分加密。這就避免了單純使用異或加密時,密鑰長度小於明文的安全性問題。 2. 密鑰在經過密鑰調度算法(KSA)和偽隨機生成算法(PRGA)後,從密鑰流逆向反推密鑰變得極度困難,這也保證了安全性。 3. 但RC4仍有許多安全問題,現已逐漸被淘汰使用其他算法。例如AES(詳見[AES&伽羅瓦域/有限域](/2uEV2ydvTK6WjrcYm1DZ1A)) ## 實作 ```cpp= #include<bits/stdc++.h> using namespace std; string key; string plaintext; string ciphertext; unsigned char K[256];//一定要unsigned,範圍才是0~255 unsigned char S[256]; void KSA(){ for(int i = 0; i < 256; i++){//初始化S盒 S[i] = i; } for(int i = 0; i < 256; i++){//擴展密鑰 K[i] = key[i % key.size()]; } int j = 0; for(int i = 0; i < 256; i++){//置換,打亂S表 j = (j + S[i] + K[i]) % 256; swap(S[i],S[j]); } return; } void PRGA_XOR(){//通過偽隨機算法PRGA int i = 0, j = 0; for(int p = 0; p < ciphertext.size(); p++){ i = (i + 1) % 256; j = (j + S[i]) % 256; swap(S[i], S[j]); unsigned char k = (S[i] + S[j]) % 256; ciphertext[p] = plaintext[p] ^ S[k]; } return; } int main(){ cout << "請輸入明文(密文)\n"; cin >> plaintext; cout << "請輸入密鑰\n"; cin >> key; KSA(); ciphertext.resize(plaintext.size()); PRGA_XOR(); cout << ciphertext << '\n'; return 0; } ``` ### 加入Base64 寫完後我發現加密完後字元陣列裡面會出現超出ASCII碼規範範圍外的數字,會導致輸出的字元為亂碼,我認為這會造成使用和解密上的麻煩所以,我就決定其進行Base64編碼。加入Base64編碼後還可以讓輸入也更自由(不用再被ASCII碼限制) >詳見:[Base64編碼](/Zs6Ltgm8QZ-LhbosB85C_Q) ```cpp= #include<bits/stdc++.h> using namespace std; //--------------Base64--------------------- int sBase64[64] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; string Base64_encode(string str){ int len = str.size(); string res; res.resize((len + 2) / 3 * 4); int j = 0; for(int i = 0; i < len / 3 * 3;i += 3){ int bits = ((str[i] & 0xff) << 16) | ((str[i+1] & 0xff) << 8) | (str[i+2] & 0xff); res[j++] = sBase64[(bits >> 18) & 0x3f]; res[j++] = sBase64[(bits >> 12) & 0x3f]; res[j++] = sBase64[(bits >> 6) & 0x3f]; res[j++] = sBase64[bits & 0x3f]; } if(len % 3 == 1){ int bits = (str[len - 1] & 0xff) << 4; res[j++] = sBase64[(bits >> 6) & 0x3f]; res[j++] = sBase64[bits & 0x3f]; res[j++] = '='; res[j] = '='; } else if(len % 3 == 2){ int bits = (str[len - 2] & 0xff) << 10 | (str[len - 1] & 0xff) << 2; res[j++] = sBase64[(bits >> 12) & 0x3f]; res[j++] = sBase64[(bits >> 6) & 0x3f]; res[j++] = sBase64[bits & 0x3f]; res[j] = '='; } return res; } unsigned char BaseValue(char c){ if(c > 'a' - 1){ return c - 'a' + 26; } else if(c > 'A' - 1){ return c - 'A'; } else if(c > '0' - 1){ return c - '0' + 52; } else if(c == '+'){ return 62; } else if(c == '/'){ return 63; } return -1; } string Base64_decode(string str){ int len = str.size(); string res; for(int i = 0; i < len - 4; i+=4){ res.push_back((BaseValue(str[i]) << 2) | (BaseValue(str[i+1]) >> 4)); res.push_back((BaseValue(str[i+1]) << 4) | (BaseValue(str[i+2]) >> 2)); res.push_back((BaseValue(str[i+2]) << 6)| (BaseValue(str[i+3]))); } res.push_back((BaseValue(str[len-4]) << 2) | (BaseValue(str[len-3]) >> 4)); if(str[len-2] != '='){ res.push_back((BaseValue(str[len-3]) << 4) | (BaseValue(str[len-2]) >> 2)); } if(str[len-1] != '='){ res.push_back((BaseValue(str[len-2]) << 6) | (BaseValue(str[len-1]))); } return res; } //--------------Base64--------------------- //---------------RC4----------------------- string ciphertext; unsigned char K[256];//一定要unsigned,範圍才是0~255 unsigned char S[256]; void KSA(string key){ for(int i = 0; i < 256; i++){//初始化S盒 S[i] = i; } for(int i = 0; i < 256; i++){//擴展密鑰 K[i] = key[i % key.size()]; } int j = 0; for(int i = 0; i < 256; i++){//置換,打亂S表 j = (j + S[i] + K[i]) % 256; swap(S[i],S[j]); } return; } void PRGA_XOR(string plaintext){ int i = 0, j = 0; for(int p = 0; p < plaintext.size(); p++){ i = (i + 1) % 256; j = (j + S[i]) % 256; swap(S[i], S[j]); unsigned char k = (S[i] + S[j]) % 256; ciphertext[p] = plaintext[p] ^ S[k]; } return; } bool isASCII(string str){ for(int i = 0; i < str.size(); i++){ if(!isprint(str[i])){ return 0; } } return 1; } //---------------RC4----------------------- int main(){ string key; string text; cout << "注:RC4為對稱為對稱加密算法,加解密使用同一組密鑰" << '\n'; //cout << "注:RC4加密不支援string輸出,容易顯示亂碼(解密支援)" << '\n'; while(1){ cout << "要進行加密請輸入0,解密請輸入1" << '\n'; int flag1;cin >> flag1; if(!flag1){//加密 cout << "輸入的明文以字節儲存(就是常見的1byte儲存一個)的請輸入0"<<'\n'; cout << "輸入的明文以Base64編碼的請輸入1" << '\n'; int flag2; cin >> flag2; cin.ignore(); cout << "請輸入明文\n"; getline(cin, text); if(flag2){ text = Base64_decode(text); } } if(flag1){//解密 cout << "請輸入Base64編碼的密文" << '\n'; cin.ignore(); getline(cin,text); text = Base64_decode(text); } cout << "請輸入密鑰(密鑰以字節儲存處理)\n"; getline(cin, key); KSA(key); ciphertext.clear(); ciphertext.resize(text.size()); PRGA_XOR(text); if(!flag1){ cout << "密文的Base64編碼:" << Base64_encode(ciphertext) << '\n'; } if(flag1){ cout << "明文為:" << ciphertext; cout.clear(); cout << '\n'; cout << "明文的Base64編碼:" << Base64_encode(ciphertext) << '\n'; } cout << "-------------" << '\n'; } return 0; } ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully