LoginSignup
8

More than 5 years have passed since last update.

GoでSecureRandomを使いたい

Last updated at Posted at 2016-11-03

Rubyの以下のコード

require 'securerandom'

puts SecureRandom.hex(16)

をGoに移植したいと思ったとします。すると以下のようになります。

package main

import (
    crand "crypto/rand"
    "fmt"
)

func secureRandomStr(b int) string {
    k := make([]byte, b)
    if _, err := crand.Read(k); err != nil {
        panic(err)
    }
    return fmt.Sprintf("%x", k)
}

func main() {
    fmt.Println(secureRandomStr(16))
}

なんでこんな話をするのかというと、以前移植する機会があったんですね。

Ruby実装は SecureRandom.hex(16) と書いてあるだけでした。実はRubyのコードもGoのコードも自分が書いたのですが、Rubyで何も考えずに書いたコードがこんなに長くなるのか!って感じで(他にも色々あって)移植作業は予想以上に大変でした。

こういう風にRubyだと1行だけど、Goだと色々しないといけないといけないみたいなパターンが色々あるので、色んな言語で実装する必要があるWebアプリケーションを実装するときは気を付けましょう、という話でした(まあ自分が悪い)。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
8