Skip to content

Add WCCipher class to handle data encryption #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package com.trustwallet.walletconnect

import com.trustwallet.walletconnect.exceptions.InvalidHmacException
import com.trustwallet.walletconnect.extensions.hexStringToByteArray
import com.trustwallet.walletconnect.extensions.toHex
import com.trustwallet.walletconnect.models.WCEncryptionPayload
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.Mac
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

private val CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding"
private val MAC_ALGORITHM = "HmacSHA256"

object WCCipher {
fun encrypt(data: ByteArray, key: ByteArray): WCEncryptionPayload {
val iv = randomBytes(16)
val keySpec = SecretKeySpec(key, "AES")
val ivSpec = IvParameterSpec(iv)
val cipher = Cipher.getInstance(CIPHER_ALGORITHM)
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec)

val encryptedData = cipher.doFinal(data)
val hmac = computeHmac(
data = encryptedData,
iv = iv,
key = key
)

return WCEncryptionPayload(
data = encryptedData.toHex(),
iv = iv.toHex(),
hmac = hmac
)
}

fun decrypt(payload: WCEncryptionPayload, key: ByteArray): ByteArray {
val data = payload.data.hexStringToByteArray()
val iv = payload.iv.hexStringToByteArray()
val computedHmac = computeHmac(
data = data,
iv = iv,
key = key
)

if (computedHmac != payload.hmac.toLowerCase()) {
throw InvalidHmacException()
}

val keySpec = SecretKeySpec(key, "AES")
val ivSpec = IvParameterSpec(iv)
val cipher = Cipher.getInstance(CIPHER_ALGORITHM)
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec)

return cipher.doFinal(data)
}

private fun computeHmac(data: ByteArray, iv: ByteArray, key: ByteArray): String {
val mac = Mac.getInstance(MAC_ALGORITHM)
val payload = data + iv
mac.init(SecretKeySpec(key, MAC_ALGORITHM))
return mac.doFinal(payload).toHex()
}

private fun randomBytes(size: Int): ByteArray {
val secureRandom = SecureRandom()
val bytes = ByteArray(size)
secureRandom.nextBytes(bytes)

return bytes
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ import com.trustwallet.walletconnect.models.session.WCApproveSessionResponse
import com.trustwallet.walletconnect.models.session.WCSession
import com.trustwallet.walletconnect.models.session.WCSessionRequest
import com.trustwallet.walletconnect.models.session.WCSessionUpdate
import com.trustwallet.walletconnect.security.decrypt
import com.trustwallet.walletconnect.security.encrypt
import okhttp3.*
import okio.ByteString
import java.util.*
Expand Down Expand Up @@ -224,7 +222,7 @@ open class WCClient (
val message = gson.fromJson<WCSocketMessage>(text)
val encrypted = gson.fromJson<WCEncryptionPayload>(message.payload)
val session = this.session ?: throw IllegalStateException("session can't be null on message receive")
return String(decrypt(encrypted, session.key.hexStringToByteArray()), Charsets.UTF_8)
return String(WCCipher.decrypt(encrypted, session.key.hexStringToByteArray()), Charsets.UTF_8)
}

private fun invalidParams(id: Long): Boolean {
Expand Down Expand Up @@ -346,7 +344,7 @@ open class WCClient (
private fun encryptAndSend(result: String): Boolean {
Log.d(TAG,"==> message $result")
val session = this.session ?: throw IllegalStateException("session can't be null on message send")
val payload = gson.toJson(encrypt(result.toByteArray(Charsets.UTF_8), session.key.hexStringToByteArray()))
val payload = gson.toJson(WCCipher.encrypt(result.toByteArray(Charsets.UTF_8), session.key.hexStringToByteArray()))
val message = WCSocketMessage(
// Once the remotePeerId is defined, all messages must be sent to this channel. The session.topic channel
// will be used only to respond the session request message.
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.trustwallet.walletconnect.security
package com.trustwallet.walletconnect

import android.os.Build
import com.trustwallet.walletconnect.extensions.hexStringToByteArray
Expand All @@ -11,7 +11,7 @@ import org.robolectric.annotation.Config

@RunWith(RobolectricTestRunner::class)
@Config(sdk = [Build.VERSION_CODES.O_MR1])
class WCEncryptorTests {
class WCCipherTests {
@Test
fun test_decrypt() {
val data = "1b3db3674de082d65455eba0ae61cfe7e681c8ef1132e60c8dbd8e52daf18f4fea42cc76366c83351dab6dca52682ff81f828753f89a21e1cc46587ca51ccd353914ffdd3b0394acfee392be6c22b3db9237d3f717a3777e3577dd70408c089a4c9c85130a68c43b0a8aadb00f1b8a8558798104e67aa4ff027b35d4b989e7fd3988d5dcdd563105767670be735b21c4"
Expand All @@ -24,7 +24,7 @@ class WCEncryptorTests {
hmac = hmac
)

val decrypted = String(decrypt(payload, key), Charsets.UTF_8)
val decrypted = String(WCCipher.decrypt(payload, key), Charsets.UTF_8)
val expected = "{\"id\":1554098597199736,\"jsonrpc\":\"2.0\",\"method\":\"wc_sessionUpdate\",\"params\":[{\"approved\":false,\"chainId\":null,\"accounts\":null}]}"
Assert.assertEquals(expected, decrypted)
}
Expand All @@ -33,8 +33,8 @@ class WCEncryptorTests {
fun test_encrypt() {
val expected = "{\"id\":1554098597199736,\"jsonrpc\":\"2.0\",\"method\":\"wc_sessionUpdate\",\"params\":[{\"approved\":false,\"chainId\":null,\"accounts\":null}]}".hexStringToByteArray()
val key = "5caa3a74154cee16bd1b570a1330be46e086474ac2f4720530662ef1a469662c".hexStringToByteArray()
val payload = encrypt(data = expected, key = key)
val decrypted = decrypt(payload, key)
val payload = WCCipher.encrypt(data = expected, key = key)
val decrypted = WCCipher.decrypt(payload, key)
Assert.assertArrayEquals(expected, decrypted)
}
}