Simply put, Cryptography provides a method for secure communication. By using cryptography, we can send secret messages to others across an insecure medium (like the internet), and be sure that only the intended recipients will be able to read the message.
In this course, we'll be writing code in Go that makes up part of "Passly", a password manager. To start, let's write a function that will debug the logic that encrypts and decrypts passwords!
We encrypt passwords so that if an attacker gains access to the computer on which the passwords are stored, they still won't be able to read the passwords.
Complete the debugEncryptDecrypt
function.
encrypt
functionEncrypted password: ENCRYPTED
, where ENCRYPTED
is the result of the encrypt
function.decrypt
functionDecrypted password: DECRYPTED
, where DECRYPTED
is the result of the decrypt
function.Make sure you terminate both lines with a newline character (\n
) if you're using fmt.Printf.
Don't worry, we'll talk about how keys, ivs, and ciphers work in more detail later.
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/hex"
"fmt"
"log"
)
func debugEncryptDecrypt(masterKey, iv, password string) {
// ?
encodeText := encrypt(password, masterKey, iv)
fmt.Println(encodeText)
decodeText := decrypt(encodeText, masterKey, iv)
fmt.Println(decodeText)
}
// don't touch below this line
func main() {
const masterKey = "kjhgfdsaqwertyuioplkjhgfdsaqwert"
const iv = "1234567812345678"
test(masterKey, iv, "k33pThisPasswordSafe")
test(masterKey, iv, "12345")
test(masterKey, iv, "thePasswordOnMyLuggage")
test(masterKey, iv, "pizza_the_HUt")
}
func test(masterKey, iv, password string) {
debugEncryptDecrypt(masterKey, iv, password)
fmt.Println("========")
}
func encrypt(plainText, key, iv string) string {
bytes := []byte(plainText)
blockCipher, err := aes.NewCipher([]byte(key))
if err != nil {
log.Println(err)
return ""
}
stream := cipher.NewCTR(blockCipher, []byte(iv))
stream.XORKeyStream(bytes, bytes)
return fmt.Sprintf("%x", bytes)
}
func decrypt(cipherText, key, iv string) string {
blockCipher, err := aes.NewCipher([]byte(key))
if err != nil {
log.Println(err)
return ""
}
stream := cipher.NewCTR(blockCipher, []byte(iv))
bytes, err := hex.DecodeString(cipherText)
if err != nil {
log.Println(err)
return ""
}
stream.XORKeyStream(bytes, bytes)
return string(bytes)
}