8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Kotlin】"AES/CBC/PKCS7Padding"での暗号化・復号化

Last updated at Posted at 2020-09-11

暗号化

fun String.encrypt(): String {
	//それぞれ16文字にする
	val secretKey = "abcdefghijklmnop"
	val initializationKey = "ABCDEFGHIJKLMNOP"
	val key = SecretKeySpec(secretKey.toByteArray(), "AES")
	val iv = IvParameterSpec(initializationKey.toByteArray())

	val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
	cipher.init(Cipher.ENCRYPT_MODE, key, iv)

	val byteResult = cipher.doFinal(this.toByteArray())

	return Base64.encodeToString(byteResult, Base64.NO_WRAP)
}

復号化

fun String.decrypt(): String {
	//それぞれ16文字にする
	val secretKey = "abcdefghijklmnop"
	val initializationKey = "ABCDEFGHIJKLMNOP"
	val key = SecretKeySpec(secretKey.toByteArray(), "AES")
	val iv = IvParameterSpec(initializationKey.toByteArray())

	val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
	cipher.init(Cipher.DECRYPT_MODE, key, iv)

	val byteResult = cipher.doFinal(Base64.decode(this, Base64.NO_WRAP))

	return String(byteResult)
}
8
4
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
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?