Go DES, AES

Goのパッケージのdes, aesを使ってみました

1. 使用したパッケージ

des : https://golang.org/pkg/crypto/des/


aes : https://golang.org/pkg/crypto/aes/
cipher : https://golang.org/pkg/crypto/cipher/

2. DES

2-1. ソースコード

package main

import (
    "bufio"
    "crypto/cipher"
    "crypto/des"
    "crypto/rand"
    "fmt"
    "io"
    "log"
    "os"
)

func main() {
    stdin := bufio.NewScanner(os.Stdin)

    fmt.Print("Plain Text: ")
    stdin.Scan()
    input := stdin.Text()
    plainText := []byte(input)

    key := []byte("12345678")

    block, err := des.NewCipher(key)
    if err != nil {
        log.Fatal(err)
    }

    encryptText := make([]byte, des.BlockSize+len(plainText))
    iv := encryptText[:des.BlockSize]
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        log.Fatal(err)
    }

    stream := cipher.NewCTR(block, iv)
    stream.XORKeyStream(encryptText[des.BlockSize:], plainText)
    fmt.Printf("Encrypt: %x\n", encryptText[des.BlockSize:])

    decryptText := make([]byte, len(plainText))
    stream = cipher.NewCTR(block, iv)
    stream.XORKeyStream(decryptText, encryptText[des.BlockSize:])
    fmt.Printf("Decrypt: %s\n", string(decryptText))
}

2-2. 注意点

keyのサイズは、8

2-3. 結果

Plain Text: This is a secret message.
Encrypt: f04195b5e817f6fa42554a66f13c2eb89a1f3f2952225540ef
Decrypt: This is a secret message.

3. AES

3-1. ソースコード

package main

import (
    "bufio"
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "fmt"
    "io"
    "log"
    "os"
)

func main() {
    stdin := bufio.NewScanner(os.Stdin)
    fmt.Print("Plain Text: ")
    stdin.Scan()
    input := stdin.Text()

    plainText := []byte(input)

    key := []byte("0123456789ABCDEF0123456789ABCDEF")

    block, err := aes.NewCipher(key)
    if err != nil {
        log.Fatal(err)
    }

    encryptText := make([]byte, aes.BlockSize+len(plainText))

    iv := encryptText[:aes.BlockSize]
    if _, err = io.ReadFull(rand.Reader, iv); err != nil {
        log.Fatal(err)
    }

    encryptStream := cipher.NewCTR(block, iv)
    encryptStream.XORKeyStream(encryptText[aes.BlockSize:], plainText)
    fmt.Printf("Encrypt: %x\n", encryptText)

    decryptText := make([]byte, len(encryptText[aes.BlockSize:]))
    decryptStream := cipher.NewCTR(block, encryptText[:aes.BlockSize])
    decryptStream.XORKeyStream(decryptText, encryptText[aes.BlockSize:])
    fmt.Printf("Decrypt: %s\n", string(decryptText))
}

3-2. 注意点

keyのサイズは、AES-128のときは16、AES-192のときは24、AES-256のときは32

3-3. 結果

Plain Text: secret password
Encrypt: 04184ec5563b8661bd9d11af93e95042f139e158bbbc2ac3bdee4b4455728d
Decrypt: secret password
スポンサーリンク
レクタングル広告(大)
レクタングル広告(大)

シェアする

  • このエントリーをはてなブックマークに追加

フォローする