6
5

More than 5 years have passed since last update.

Groovyで文字列やファイルを暗号化・復号化する

Posted at

Javaの標準暗号化APIを使うので目新しい所はないけど、Groovyだとサクッと試せる点が良かった。

ホントは、暗号化モードをデフォルトのECBモードじゃなくて、CBCモードぐらいの方が良いんだろうけど、とりあえずの暗号化・復号化ということで。

CBCモードに変更するのは、ソースコードとしては難しくないんだけど、実際の開発時には、IVをどこにどう保存するかが悩ましい…。

文字列の暗号化

def target = "testtest_test"
def encodeKey = encode(target.getBytes(), key)

def crypt(byte[] bytes, SecretKeySpec key) {
  def cph = Cipher.getInstance("AES")
  cph.init(Cipher.ENCRYPT_MODE, key)

  return cph.doFinal(bytes)
}

暗号化文字列の復号化

println new String(decode(encodeKey, key))

def decrypt(byte[] bytes, SecretKeySpec key) {
  def cph = Cipher.getInstance("AES")
  cph.init(Cipher.DECRYPT_MODE, key)

  return cph.doFinal(bytes)
}

ファイルの暗号化

def fileByte = new File("hoge.gif").getBytes()
// cryptメソッドは文字列の時と同じ
def encFile = crypt(fileByte, key)

new File("hoge_crypt.gif").setBytes(encFile)

暗号化ファイルの復号化

// decryptメソッドは文字列の時と同じ
def decFile = decrypt(encFile, key)
new File("hoge_decrypt.gif").setBytes(decFile)

全コード

import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import java.nio.charset.Charset

final String keyword = "encodekey1234567"
SecretKeySpec key = new SecretKeySpec(keyword.getBytes(Charset.forName("UTF-8")), "AES")

// 文字列を暗号化 → 復号化
def target = "testtest_test"
def encodeKey = encode(target.getBytes(), key)
println new String(decode(encodeKey, key))

// ファイルを暗号化 → 復号化
def fileByte = new File("hoge.gif").getBytes()
def encFile = encode(fileByte, key)

new File("hoge_crypt.gif").setBytes(encFile)

def decFile = decode(encFile, key)
new File("hoge_decrypt.gif").setBytes(decFile)

// 暗号化
def crypt(byte[] bytes, SecretKeySpec key) {
  def cph = Cipher.getInstance("AES")
  cph.init(Cipher.ENCRYPT_MODE, key)

  return cph.doFinal(bytes)
}

// 復号化
def decrypt(byte[] bytes, SecretKeySpec key) {
  def cph = Cipher.getInstance("AES")
  cph.init(Cipher.DECRYPT_MODE, key)

  return cph.doFinal(bytes)
}
6
5
0

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
  3. You can use dark theme
What you can do with signing up
6
5