Skip to content

Instantly share code, notes, and snippets.

@syossan27
Last active December 22, 2018 04:43
Show Gist options
  • Select an option

  • Save syossan27/8d0f729a35dc35921f4908da8a6ed08a to your computer and use it in GitHub Desktop.

Select an option

Save syossan27/8d0f729a35dc35921f4908da8a6ed08a to your computer and use it in GitHub Desktop.
type Connection struct {
Name string `yaml:"name"`
Host string `yaml:"host"`
User string `yaml:"user"`
Password string `yaml:"password"`
}
type Connections []Connection
// Load connections
func Load() Connections {
// AES暗号の鍵として.ssh/id_rsaの内容を取得する
key := foundation.GetKey(foundation.KeyPath)
// 接続情報管理ファイルの内容を取得する
p, err := ioutil.ReadFile(foundation.StorePath)
if err != nil {
foundation.PrintError("Failed to read store file")
}
if len(p) == 0 {
return nil
}
// 鍵を用いて接続情報管理ファイルを復号
dec, err := foundation.Decrypt(key, string(p))
if err != nil {
foundation.PrintError("Failed to decrypt connections")
}
// 復号した内容をConnectionsにマッピングする
var cs Connections
err = yaml.Unmarshal(dec, &cs)
if err != nil {
foundation.PrintError("Failed to unmarshal connections yaml")
}
return cs
}
func GetKey(path string) []byte {
p, err := ioutil.ReadFile(path)
if err != nil {
PrintError("Failed to read AES key file")
}
return GenKey(p)
}
// ハッシュ化
func GenKey(src []byte) []byte {
hash := sha256.Sum256(src)
return hash[:]
}
func Decrypt(key []byte, encrypted string) ([]byte, error) {
// 文字列をbase64デコード
data, err := base64.StdEncoding.DecodeString(encrypted)
if err != nil {
return nil, err
}
// ブロック・サイファーでのブロックの生成
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
iv := data[:aes.BlockSize] // 初期化ベクトル(IV)
src := data[aes.BlockSize:] // IVを除いた暗号データ
dst := make([]byte, len(src)) // srcのバイト配列を確保
stream := cipher.NewCTR(block, iv) // CTRモードで鍵ストリームを生成
stream.XORKeyStream(dst, src) // 暗号データに対して排他的論理和をかけることで平文を取得
return dst, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment