android中websockets的证书固定
Posted
技术标签:
【中文标题】android中websockets的证书固定【英文标题】:Certificate pinning for websockets in android 【发布时间】:2019-12-30 07:47:11 【问题描述】:我们在我的一个 android 应用程序中使用 websockets。使用第 3 方库“https://github.com/TakahikoKawasaki/nv-websocket-client”。
现在我们想要为 websocket 启用 ssl pinning。 我们应该怎么做?
谢谢
【问题讨论】:
【参考方案1】:We can enable ssl pinning for web sockets using sslContext.
This is my working code.
----------
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(null, arrayOf(CustomTrustManager(null)), SecureRandom())
mSocketFactory.sslContext = sslContext
val ws = mSocketFactory.createSocket(presentEndpoint)
class CustomTrustManager(keyStore: KeyStore?) : X509TrustManager
private val tag = CustomTrustManager::class.java.canonicalName
init
val factory: TrustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
factory.init(keyStore)
val trustmanagers: Array<TrustManager> = factory.trustManagers
if (trustmanagers.isEmpty())
throw NoSuchAlgorithmException("no trust manager found")
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?)
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?)
for (certificate in chain!!)
if (isValidPin(certificate))
return
throw CertificateException("No valid pins found in chain!")
override fun getAcceptedIssuers(): Array<X509Certificate>?
return null
private fun isValidPin(certificate: X509Certificate): Boolean
return try
val md = MessageDigest.getInstance("SHA-256")
val publicKey = certificate.publicKey.encoded
md.update(publicKey, 0, publicKey.size)
val pin = Base64.encodeToString(md.digest(), Base64.NO_WRAP)
val validPins = Collections.singleton(Constants.PK)
if (validPins.contains("sha256/$pin"))
return true
false
catch (ex: NoSuchAlgorithmException)
throw CertificateException(ex)
【讨论】:
以上是关于android中websockets的证书固定的主要内容,如果未能解决你的问题,请参考以下文章