Skip to content

Instantly share code, notes, and snippets.

@TomoyaShibata
Last active January 10, 2018 06:38
Show Gist options
  • Save TomoyaShibata/f55c6155194249213d8ab9a3739a174b to your computer and use it in GitHub Desktop.
Save TomoyaShibata/f55c6155194249213d8ab9a3739a174b to your computer and use it in GitHub Desktop.
Android で NIST P-256 を使った公開鍵暗号を元に生成した共有秘密鍵で暗号化/復号するコード
import android.util.Log
import java.security.interfaces.ECPublicKey
import javax.crypto.Cipher
import javax.crypto.KeyAgreement
import javax.crypto.spec.SecretKeySpec
// Alice のキーペア作成
val aliceKpg = KeyPairGenerator.getInstance("EC")
aliceKpg.initialize(ECGenParameterSpec("secp256r1"))
val aliceKeyPair = aliceKpg.generateKeyPair()
val alicePublicKey = aliceKeyPair.public as ECPublicKey
// Bob のキーペア作成
val bobKpg = KeyPairGenerator.getInstance("EC")
bobKpg.initialize(ECGenParameterSpec("secp256r1"))
val bobKeyPair = bobKpg.generateKeyPair()
val bobPublicKey = bobKeyPair.public as ECPublicKey
// Alice の秘密鍵と Bob の公開鍵を使って Alice の共有秘密鍵作成
val aliceKeyAgreement = KeyAgreement.getInstance("ECDH")
aliceKeyAgreement.init(aliceKeyPair.private)
aliceKeyAgreement.doPhase(bobPublicKey, true)
val aliceSharedSecret = aliceKeyAgreement.generateSecret("AES")
Log.d("aliceSharedSecret", String(aliceSharedSecret.encoded))
// Bob の秘密鍵と Alice の公開鍵を使って Bob の共有秘密鍵作成
val bobKeyAgreement = KeyAgreement.getInstance("ECDH")
bobKeyAgreement.init(bobKeyPair.private)
bobKeyAgreement.doPhase(alicePublicKey, true)
val bobSharedSecret = bobKeyAgreement.generateSecret("AES")
Log.d("bobSharedSecret", String(bobSharedSecret.encoded))
Log.d("algorithm", bobSharedSecret.algorithm)
// Alice の共有秘密鍵を使って暗号化
val encryptCipher = Cipher.getInstance("AES")
encryptCipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(aliceSharedSecret.encoded, aliceSharedSecret.algorithm))
val encrypted = encryptCipher.doFinal(this.plainText.toByteArray())
Log.d("encrypted", String(encrypted))
// Bob の共有秘密鍵を使って復号
val decryptCipher = Cipher.getInstance("AES")
decryptCipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(bobSharedSecret.encoded, bobSharedSecret.algorithm))
val decrypted = decryptCipher.doFinal(encrypted)
Log.d("decrypted", String(decrypted))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment