Tony041010
    • 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
    • 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 Versions and GitHub Sync Note Insights 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- tags: 2022CRC title: Python實作五:Password Manager slideOptions: transition: slide theme: --- # Python實作課程 ## 第七堂課 : Password Manager ## 2022 / 6 / 17 ### Tony --- # 古典密碼 ## 維吉尼亞密碼 a.k.a進階版凱薩密碼 ---- 加密原理 : 明文、密鑰:由字母組成的字串 把 A 到 Z 編號成 0 到 25 明文中第一個字母的位移量就是密鑰第一個字母的**編號**、 第二個字母的位移量就是密鑰第二個字母的**編號**、…… 如果密鑰長度比明文字母數短 就再從**第一個字母**開始用 ---- 明文:HSNU CRC 密鑰:CRSC **明文 H S N U C R C** 密鑰 C R S C C R S 密文 J J F W E I U ---- 因為每一個字母的位移量都不盡相同 所以不知道密鑰的情況下 要還原出明文是很困難的事 幾乎不可能 ---- ## 維吉尼亞表格 ![](https://i.imgur.com/uY2i7bO.png =30%x) --- # 實作維吉尼亞密碼 ---- 要怎麼把字母位移? ---- 我們利用**ASCII**(美國資訊交換標準代碼) ![](https://i.imgur.com/ZWjKrQG.gif =50%x) ---- 找到字元 c 對應的數字:ord(c) 找到數字 i 對應的字元:chr(i) ---- 純字母版 ```python= def encryption(key, password): cipher = "" now = 0 for char in password: t = ord(char) - ord('A') k = ord( key[now] ) - ord('A') print(t+k) cipher += chr( ord('A') + (t+k)%26 ) now = (now + 1) % len(key) return cipher def decryption(key, password): cipher = "" now = 0 for char in password: t = ord(char) - ord('A') k = ord( key[now] ) - ord('A') print(t-k) cipher += chr( ord('A') + (t-k)%26) now = (now + 1) % len(key) return cipher ``` ---- 廣泛版(不局限於字母) ```python= def encryption(key, password): cipher = "" now = 0 for char in password: k = ord( key[now] ) - ord('A') cipher += chr( (ord(char) + k)%126 ) now = (now + 1) % len(key) return cipher def decryption(key, password): cipher = "" now = 0 for char in password: k = ord( key[now] ) - ord('A') cipher += chr( (ord(char) - k)%126 ) now = (now + 1) % len(key) return cipher ``` 我們將用它來加密/解密我們的密碼 --- # Password Manager ---- 有時候在很多網站創建很多帳號 其中每種帳號的密碼限制都不一樣 時間久了很容易忘記 這種時候就很需要Password Manager的幫忙 ---- Process: 1. 輸入Master password (用戶名,也是到時候加解密的key) 2. 選擇瀏覽密碼還是新增密碼 3. 如果新增密碼,輸入帳號名稱跟密碼,把密碼依照維吉尼亞密碼規定加密後連同帳號名稱存入記事本 4. 如果瀏覽密碼,把目前所有的密碼解密之後連同帳號名稱秀出來 5. 都沒事了就按q退出 如果master password輸入錯誤,就會無法看到既有的密碼 --- # 開始寫Code ---- 1. 輸入master password ```python= key = input("What is the master password?") ``` ---- 2. 選擇瀏覽密碼還是加新密碼 ```python= while True: mode= input("Would you like to add a new password or view existing ones (view, add), press q to quit? ").lower() if mode == 'q': break if mode == "view": view(key) elif mode == "add": add(key) else: print("Valid mode.") continue ``` ---- 加解密函式 ```python= def encryption(key, password): cipher = "" now = 0 for char in password: k = ord( key[now] ) - ord('A') cipher += chr( (ord(char) + k)%126 ) now = (now + 1) % len(key) return cipher def decryption(key, password): cipher = "" now = 0 for char in password: k = ord( key[now] ) - ord('A') cipher += chr( (ord(char) - k)%126 ) now = (now + 1) % len(key) return cipher ``` ---- add()函式 在`password.txt` 中新加一條密碼,包含用戶名稱跟密碼 * `with open("password.txt", 'a') as file:` 打開一個文件檔並做事情,把他想成一個if 執行結束之後`password.txt`就會自動被關掉,很方便 輸入完會請使用者再確認一次 ---- ```python= def add(key): print('') Done = False while not Done: name = input("Account name : ") password = input("Password : ") print('') print("Please double check the account name and password you\'ve typed in :") print("Account name :", name) print("Password :", password) correct = input("Type \"yes\" if they're correct, \"no\" if they're not : ").lower() print('') if correct == "yes": encrypted_password = encryption(key, password) # like a function. Once it's done, the file will be closed automatically. # a stands for "pen". Add sth to an existing file or create a new file if the file doesn't exist. # w stands for "write". Create a file or overwrite the file # r stands for "read". Just read. with open("password.txt", 'a') as file: file.write(name + '|' + encrypted_password + '\n') # 寫入密碼 Done = True elif correct == "no": print("Alright. Please type again.") continue else: print("Valid reaction.") continue ``` ---- `view()`函式 把目前所有密碼都依照輸入的key解密後秀出來 * `file.readlines(len)` : 取得文字檔file的所有文字,len默認是-1,代表所有行數 * `line.split('|')` : 把line依照'|'切割成n個不同字元,大多數密碼不會包含'|',所以假設只利用原先用來分割的'|'切割出兩個字串 * `line.rstrip()` : 去除line最後面的指定部分,默認是空白、換行等等 ---- ```python= def view(key): print('') with open("password.txt", 'r') as file: for line in file.readlines(): data = line.rstrip() # delete the '\n' behind ecery line user, password = data.split('|') # "FB|123456789" -> ["FB", "123456789"] password = decryption(key, password) print("Account name :", user, "| Password :", password) print('') ``` 恭喜各位完成Password Manager, 可以自己多加一些有趣的功能

    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