feat: 控制通道接入 TLS 并按自签证书指纹校验
- rust_core:PinnedTlsStream 增加指纹校验、accept、读超时与关闭;会话层新增客户端连接入口 - rust_core:demo 服务按指纹选择 TLS 或明文(首字节 0x16 判定),新增 ttstd_demo_set_tls_fingerprint(ABI 5) - rust_core:发现结构补齐 tls_fingerprint,mDNS TXT 收发 tls=,信标 JSON 序列化 tls - android_receiver:新增 TlsIdentity 生成并持久化 P-256 自签证书,TlsServerTransport 用 SSLEngine 包装 Socket - android_receiver:被控端反连时窥探首字节决定 TLS/明文,信标与配对码公布 tls 指纹 - flutter_sender:NativeCore 暴露 setTlsFingerprint,连接前按目标设备指纹设置,为空则明文 - docs:README 补充 TLS 角色反转、tls 字段与 fp/tls 的区别
This commit is contained in:
1 parent
9a82766fa2
commit
e2020ab595
20 files changed
+771
-36
No files matched your search
@@ -72,4 +72,8 @@ dependencies {
|
||||
implementation("org.jetbrains.kotlin:kotlin-stdlib:2.0.21")
|
||||
// 配对二维码(纯 Java 编码,无额外传递依赖)。
|
||||
implementation("com.google.zxing:core:3.5.4")
|
||||
// 生成/解析 TLS 自签证书(只用于本机身份,不做证书链校验)。
|
||||
implementation("org.bouncycastle:bcprov-jdk18on:1.80.2")
|
||||
implementation("org.bouncycastle:bcutil-jdk18on:1.80.2")
|
||||
implementation("org.bouncycastle:bcpkix-jdk18on:1.80.2")
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import com.ttstd.lancast.receiver.util.DeviceIdentity
|
||||
import com.ttstd.lancast.receiver.util.Fingerprint
|
||||
import com.ttstd.lancast.receiver.util.Privileged
|
||||
import com.ttstd.lancast.receiver.util.QrCode
|
||||
import com.ttstd.lancast.receiver.util.TlsIdentity
|
||||
import java.net.NetworkInterface
|
||||
|
||||
class MainActivity : Activity() {
|
||||
@@ -283,6 +284,7 @@ class MainActivity : Activity() {
|
||||
fingerprint = Fingerprint.of(this),
|
||||
deviceId = DeviceIdentity.of(this),
|
||||
name = "Android Receiver",
|
||||
tlsFingerprint = TlsIdentity.fingerprintOrEmpty(this),
|
||||
)
|
||||
}
|
||||
val pairingText = if (pairingUri.isEmpty()) {
|
||||
|
||||
+2
@@ -24,6 +24,7 @@ import com.ttstd.lancast.receiver.protocol.MirrorAction
|
||||
import com.ttstd.lancast.receiver.util.DeviceIdentity
|
||||
import com.ttstd.lancast.receiver.util.Fingerprint
|
||||
import com.ttstd.lancast.receiver.util.Privileged
|
||||
import com.ttstd.lancast.receiver.util.TlsIdentity
|
||||
|
||||
/**
|
||||
* 常驻前台服务。分两个阶段:
|
||||
@@ -280,6 +281,7 @@ class MediaProjectionService : Service() {
|
||||
model = Build.MODEL ?: "Android",
|
||||
resolution = "${metrics.widthPixels}x${metrics.heightPixels}",
|
||||
fingerprint = Fingerprint.of(this),
|
||||
tlsFingerprint = TlsIdentity.fingerprintOrEmpty(this),
|
||||
),
|
||||
).also { it.start() }
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import com.ttstd.lancast.receiver.protocol.ControlEvent
|
||||
import com.ttstd.lancast.receiver.session.ReceiverTransport
|
||||
import com.ttstd.lancast.receiver.util.DeviceIdentity
|
||||
import com.ttstd.lancast.receiver.util.Fingerprint
|
||||
import com.ttstd.lancast.receiver.util.TlsIdentity
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.Executors
|
||||
@@ -70,6 +71,8 @@ class ReceiverSession(
|
||||
private val fingerprint: String = Fingerprint.of(context)
|
||||
/** 稳定的设备 id(首次运行生成后持久化),保证 pinning 能对上同一台设备。 */
|
||||
private val deviceId: String = DeviceIdentity.of(context)
|
||||
/** 控制通道 TLS 自签身份;生成失败时控制通道退回明文。 */
|
||||
private val tlsIdentity: TlsIdentity? = TlsIdentity.of(context)
|
||||
|
||||
@Volatile
|
||||
private var transport: ReceiverTransport? = null
|
||||
@@ -282,6 +285,7 @@ class ReceiverSession(
|
||||
),
|
||||
model = Build.MODEL,
|
||||
resolution = "${size[0]}x${size[1]}",
|
||||
tlsFingerprint = tlsIdentity?.fingerprint ?: "",
|
||||
)
|
||||
// 信令服务器是跨网段兜底:没有配置(空串)时不必启动,避免无谓的失败请求。
|
||||
if (signalingUrl.isNotBlank()) {
|
||||
@@ -317,6 +321,7 @@ class ReceiverSession(
|
||||
fileService,
|
||||
signalingUrl,
|
||||
deviceId,
|
||||
tlsIdentity,
|
||||
)
|
||||
created.onMirrorEvent = { action, message -> onMirrorRequest?.invoke(action, message) }
|
||||
created.onSessionConfig = { json -> applySessionConfig(json) }
|
||||
|
||||
+2
@@ -10,4 +10,6 @@ data class AnnouncedDevice(
|
||||
val capabilities: List<String>,
|
||||
val model: String,
|
||||
val resolution: String,
|
||||
/** TLS 自签证书的 SHA-256;为空表示不支持 TLS。 */
|
||||
val tlsFingerprint: String = "",
|
||||
)
|
||||
@@ -35,6 +35,8 @@ class HostBeacon(
|
||||
val resolution: String,
|
||||
/** 应用签名证书指纹,主控端据此做 TOFU pinning。 */
|
||||
val fingerprint: String = "",
|
||||
/** TLS 自签证书 SHA-256,主控端据此校验控制通道加密。 */
|
||||
val tlsFingerprint: String = "",
|
||||
)
|
||||
|
||||
companion object {
|
||||
@@ -162,6 +164,7 @@ class HostBeacon(
|
||||
put("media", mediaPort)
|
||||
put("audio", audioPort)
|
||||
put("fp", device.fingerprint)
|
||||
if (device.tlsFingerprint.isNotBlank()) put("tls", device.tlsFingerprint)
|
||||
put(
|
||||
"cap",
|
||||
JSONArray(
|
||||
|
||||
+1
@@ -40,6 +40,7 @@ class NsdAdvertiser(private val context: Context, private val device: AnnouncedD
|
||||
setAttribute("res", device.resolution)
|
||||
setAttribute("model", device.model)
|
||||
setAttribute("fp", device.fingerprint)
|
||||
if (device.tlsFingerprint.isNotBlank()) setAttribute("tls", device.tlsFingerprint)
|
||||
setAttribute("cport", device.controlPort.toString())
|
||||
setAttribute("mport", device.mediaPort.toString())
|
||||
device.ip.takeIf { it.isNotBlank() }?.let { setAttribute("ip", it) }
|
||||
|
||||
+1
@@ -52,6 +52,7 @@ class ReceiverAnnouncer(
|
||||
put("mediaPort", device.mediaPort)
|
||||
put("controlPort", device.controlPort)
|
||||
put("fp", device.fingerprint)
|
||||
if (device.tlsFingerprint.isNotBlank()) put("tls", device.tlsFingerprint)
|
||||
put("cap", JSONArray(device.capabilities))
|
||||
put("model", device.model)
|
||||
put("res", device.resolution)
|
||||
|
||||
+45
-2
@@ -9,9 +9,11 @@ import com.ttstd.lancast.receiver.input.InputInjector
|
||||
import com.ttstd.lancast.receiver.protocol.ControlEvent
|
||||
import com.ttstd.lancast.receiver.protocol.ControlFrames
|
||||
import com.ttstd.lancast.receiver.protocol.MirrorAction
|
||||
import com.ttstd.lancast.receiver.util.TlsIdentity
|
||||
import org.json.JSONObject
|
||||
import java.io.DataInputStream
|
||||
import java.io.DataOutputStream
|
||||
import java.io.PushbackInputStream
|
||||
import java.net.DatagramPacket
|
||||
import java.net.DatagramSocket
|
||||
import java.net.InetSocketAddress
|
||||
@@ -43,6 +45,8 @@ class ReceiverTransport(
|
||||
private val fileService: FileService,
|
||||
private val signalingUrl: String = "",
|
||||
private val deviceId: String = "",
|
||||
/** 控制通道 TLS 身份;为空时只接受明文对端。 */
|
||||
private val tlsIdentity: TlsIdentity? = null,
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "ReceiverTransport"
|
||||
@@ -58,6 +62,9 @@ class ReceiverTransport(
|
||||
|
||||
/** 中继会话内的轮询间隔。 */
|
||||
private const val RELAY_POLL_MS = 120L
|
||||
|
||||
/** TLS 握手记录(ClientHello)的首字节。 */
|
||||
private const val TLS_HANDSHAKE_RECORD = 0x16
|
||||
}
|
||||
|
||||
/** 握手阶段失败:对端未就绪/已断开,属于可预期情况。 */
|
||||
@@ -167,8 +174,44 @@ class ReceiverTransport(
|
||||
connect(InetSocketAddress(host, controlPort), 5000)
|
||||
}
|
||||
socket = raw
|
||||
output = DataOutputStream(raw.outputStream)
|
||||
val input = DataInputStream(raw.inputStream)
|
||||
// 主控端如果支持 TLS,会直接发 ClientHello(首字节 0x16);老版本先发 ECDH 公钥(0x04)。
|
||||
// 用回推流窥探一个字节,两种对端都能兼容。
|
||||
val rawInput = PushbackInputStream(raw.inputStream, 1)
|
||||
val first = try {
|
||||
rawInput.read()
|
||||
} catch (error: Exception) {
|
||||
throw HandshakeException("读取主控端握手首字节失败", error)
|
||||
}
|
||||
if (first < 0) {
|
||||
throw HandshakeException("主控端在握手阶段关闭了连接", java.io.EOFException())
|
||||
}
|
||||
rawInput.unread(first)
|
||||
val inputStream: java.io.InputStream
|
||||
val outputStream: java.io.OutputStream
|
||||
if (first == TLS_HANDSHAKE_RECORD) {
|
||||
val identity = tlsIdentity
|
||||
if (identity == null) {
|
||||
throw HandshakeException("主控端要求 TLS,但本机证书不可用", java.io.IOException("tls"))
|
||||
}
|
||||
try {
|
||||
val tls = TlsServerTransport(
|
||||
rawInput,
|
||||
raw.outputStream,
|
||||
identity.certificate,
|
||||
identity.privateKey,
|
||||
)
|
||||
inputStream = tls.inputStream
|
||||
outputStream = tls.outputStream
|
||||
Log.i(TAG, "控制通道已启用 TLS(${identity.fingerprint})")
|
||||
} catch (error: Exception) {
|
||||
throw HandshakeException("TLS 握手失败:${error.message}", error)
|
||||
}
|
||||
} else {
|
||||
inputStream = rawInput
|
||||
outputStream = raw.outputStream
|
||||
}
|
||||
output = DataOutputStream(outputStream)
|
||||
val input = DataInputStream(inputStream)
|
||||
|
||||
// ECDH 握手:先发本地公钥,再读取对端 65 字节公钥。
|
||||
// 对端在这期间关闭连接(主控端未开监听、正在重启、或只接受一路连接)都属于
|
||||
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
package com.ttstd.lancast.receiver.session
|
||||
|
||||
import android.util.Log
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.security.KeyStore
|
||||
import java.security.PrivateKey
|
||||
import java.security.cert.X509Certificate
|
||||
import javax.net.ssl.KeyManagerFactory
|
||||
import javax.net.ssl.SSLContext
|
||||
import javax.net.ssl.SSLEngine
|
||||
import javax.net.ssl.SSLEngineResult
|
||||
import javax.net.ssl.SSLException
|
||||
|
||||
/**
|
||||
* 在**已建立的 TCP 连接**上跑 TLS 服务端(被控端反连主控端,但 TLS 角色是服务端)。
|
||||
*
|
||||
* JSSE 没有「把已连接 Socket 升级成 TLS」的公开 API,所以这里直接用 [SSLEngine]
|
||||
* 手工驱动握手与加解密,并包装成普通 [InputStream]/[OutputStream],
|
||||
* 让上层控制通道的读写代码完全不用关心 TLS。
|
||||
*
|
||||
* 线程模型:读只发生在控制读线程,写可能来自多个发送线程;[engine] 的调用统一加锁,
|
||||
* 但阻塞的 raw 读取放在锁外,避免空闲时把写端一起卡住。
|
||||
*/
|
||||
class TlsServerTransport(
|
||||
private val rawIn: InputStream,
|
||||
private val rawOut: OutputStream,
|
||||
certificate: X509Certificate,
|
||||
privateKey: PrivateKey,
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "TlsServerTransport"
|
||||
private const val HANDSHAKE_TIMEOUT_MS = 10_000L
|
||||
private const val MIN_BUFFER = 64 * 1024
|
||||
}
|
||||
|
||||
private val engine: SSLEngine = createEngine(certificate, privateKey)
|
||||
private var netIn = ByteBuffer.allocate(maxOf(engine.session.packetBufferSize, MIN_BUFFER))
|
||||
private var netOut = ByteBuffer.allocate(maxOf(engine.session.packetBufferSize, MIN_BUFFER))
|
||||
private val appScratch = ByteBuffer.allocate(maxOf(engine.session.applicationBufferSize, MIN_BUFFER))
|
||||
private val engineLock = Any()
|
||||
|
||||
private var pending = ByteArray(0)
|
||||
private var pendingOffset = 0
|
||||
@Volatile
|
||||
private var closed = false
|
||||
|
||||
val inputStream: InputStream = object : InputStream() {
|
||||
override fun read(): Int {
|
||||
val one = ByteArray(1)
|
||||
val read = read(one, 0, 1)
|
||||
return if (read <= 0) -1 else one[0].toInt() and 0xff
|
||||
}
|
||||
|
||||
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
|
||||
if (length == 0) return 0
|
||||
if (offset < 0 || length < 0 || offset + length > buffer.size) {
|
||||
throw IndexOutOfBoundsException()
|
||||
}
|
||||
while (true) {
|
||||
if (pendingOffset < pending.size) {
|
||||
val count = minOf(length, pending.size - pendingOffset)
|
||||
System.arraycopy(pending, pendingOffset, buffer, offset, count)
|
||||
pendingOffset += count
|
||||
return count
|
||||
}
|
||||
pending = ByteArray(0)
|
||||
pendingOffset = 0
|
||||
if (!unwrapOnce()) return -1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val outputStream: OutputStream = object : OutputStream() {
|
||||
override fun write(b: Int) = write(byteArrayOf(b.toByte()), 0, 1)
|
||||
|
||||
override fun write(buffer: ByteArray, offset: Int, length: Int) {
|
||||
if (length == 0) return
|
||||
val source = ByteBuffer.wrap(buffer, offset, length)
|
||||
while (source.hasRemaining()) {
|
||||
netOut.clear()
|
||||
val result = synchronized(engineLock) { engine.wrap(source, netOut) }
|
||||
flushNet()
|
||||
if (result.status == SSLEngineResult.Status.BUFFER_OVERFLOW) {
|
||||
growNetOut()
|
||||
continue
|
||||
}
|
||||
if (result.status == SSLEngineResult.Status.CLOSED) {
|
||||
throw SSLException("TLS 通道已关闭")
|
||||
}
|
||||
}
|
||||
runCatching { rawOut.flush() }
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
handshake()
|
||||
}
|
||||
|
||||
private fun createEngine(certificate: X509Certificate, privateKey: PrivateKey): SSLEngine {
|
||||
val store = KeyStore.getInstance(KeyStore.getDefaultType()).apply { load(null, null) }
|
||||
store.setKeyEntry("ttstd", privateKey, charArrayOf(), arrayOf(certificate))
|
||||
val factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
|
||||
factory.init(store, charArrayOf())
|
||||
val context = SSLContext.getInstance("TLS")
|
||||
context.init(factory.keyManagers, null, null)
|
||||
return context.createSSLEngine().apply {
|
||||
useClientMode = false
|
||||
needClientAuth = false
|
||||
}
|
||||
}
|
||||
|
||||
private fun handshake() {
|
||||
synchronized(engineLock) { engine.beginHandshake() }
|
||||
val deadline = System.currentTimeMillis() + HANDSHAKE_TIMEOUT_MS
|
||||
while (true) {
|
||||
val status = synchronized(engineLock) { engine.handshakeStatus }
|
||||
if (status == SSLEngineResult.HandshakeStatus.FINISHED ||
|
||||
status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING
|
||||
) {
|
||||
Log.d(TAG, "TLS 握手完成")
|
||||
return
|
||||
}
|
||||
if (System.currentTimeMillis() > deadline) {
|
||||
throw SSLException("TLS 握手超时")
|
||||
}
|
||||
when (status) {
|
||||
SSLEngineResult.HandshakeStatus.NEED_WRAP -> wrapPending()
|
||||
SSLEngineResult.HandshakeStatus.NEED_UNWRAP -> {
|
||||
if (!unwrapOnce()) throw SSLException("对端在 TLS 握手阶段断开")
|
||||
}
|
||||
SSLEngineResult.HandshakeStatus.NEED_TASK -> runTasks()
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @return false 表示对端已关闭连接。 */
|
||||
private fun unwrapOnce(): Boolean {
|
||||
appScratch.clear()
|
||||
netIn.flip()
|
||||
val result = synchronized(engineLock) { engine.unwrap(netIn, appScratch) }
|
||||
netIn.compact()
|
||||
when (result.status) {
|
||||
SSLEngineResult.Status.CLOSED -> {
|
||||
closed = true
|
||||
return false
|
||||
}
|
||||
SSLEngineResult.Status.BUFFER_UNDERFLOW -> {
|
||||
if (!readRaw()) {
|
||||
closed = true
|
||||
return false
|
||||
}
|
||||
}
|
||||
SSLEngineResult.Status.BUFFER_OVERFLOW -> throw SSLException("TLS 应用缓冲区不足")
|
||||
SSLEngineResult.Status.OK -> {
|
||||
if (appScratch.position() > 0) {
|
||||
appScratch.flip()
|
||||
val produced = ByteArray(appScratch.remaining())
|
||||
appScratch.get(produced)
|
||||
pending = produced
|
||||
pendingOffset = 0
|
||||
}
|
||||
runTasks()
|
||||
if (synchronized(engineLock) { engine.handshakeStatus } ==
|
||||
SSLEngineResult.HandshakeStatus.NEED_WRAP
|
||||
) {
|
||||
wrapPending()
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** 读一段 TLS 记录;返回 false 表示 EOF。 */
|
||||
private fun readRaw(): Boolean {
|
||||
if (!netIn.hasRemaining()) {
|
||||
val bigger = ByteBuffer.allocate(netIn.capacity() * 2)
|
||||
netIn.flip()
|
||||
bigger.put(netIn)
|
||||
netIn = bigger
|
||||
}
|
||||
val read = rawIn.read(netIn.array(), netIn.position(), netIn.remaining())
|
||||
if (read < 0) return false
|
||||
if (read > 0) netIn.position(netIn.position() + read)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun wrapPending() {
|
||||
netOut.clear()
|
||||
var result: SSLEngineResult
|
||||
do {
|
||||
result = synchronized(engineLock) { engine.wrap(ByteBuffer.allocate(0), netOut) }
|
||||
flushNet()
|
||||
} while (result.status == SSLEngineResult.Status.BUFFER_OVERFLOW)
|
||||
if (result.status == SSLEngineResult.Status.CLOSED) closed = true
|
||||
}
|
||||
|
||||
private fun flushNet() {
|
||||
if (netOut.position() == 0) return
|
||||
netOut.flip()
|
||||
rawOut.write(netOut.array(), 0, netOut.limit())
|
||||
rawOut.flush()
|
||||
netOut.clear()
|
||||
}
|
||||
|
||||
private fun growNetOut() {
|
||||
val bigger = ByteBuffer.allocate(netOut.capacity() * 2)
|
||||
netOut.flip()
|
||||
bigger.put(netOut)
|
||||
netOut = bigger
|
||||
}
|
||||
|
||||
private fun runTasks() {
|
||||
while (true) {
|
||||
val task = synchronized(engineLock) { engine.delegatedTask } ?: return
|
||||
task.run()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.ttstd.lancast.receiver.util
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Base64
|
||||
import android.util.Log
|
||||
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter
|
||||
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder
|
||||
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder
|
||||
import java.io.File
|
||||
import java.math.BigInteger
|
||||
import java.security.KeyFactory
|
||||
import java.security.KeyPairGenerator
|
||||
import java.security.MessageDigest
|
||||
import java.security.PrivateKey
|
||||
import java.security.SecureRandom
|
||||
import java.security.cert.CertificateFactory
|
||||
import java.security.cert.X509Certificate
|
||||
import java.security.spec.ECGenParameterSpec
|
||||
import java.security.spec.PKCS8EncodedKeySpec
|
||||
import java.util.Date
|
||||
|
||||
/**
|
||||
* 控制通道 TLS 身份:一台设备一份自签 EC 证书,首次运行生成后持久化。
|
||||
*
|
||||
* 证书只用于**传输加密**,信任来自主控端发现结果里的 `tls` 指纹(TOFU):
|
||||
* 不做 CA 链校验,也不用它替代应用签名指纹 `fp`。
|
||||
*/
|
||||
class TlsIdentity(
|
||||
val certificate: X509Certificate,
|
||||
val privateKey: PrivateKey,
|
||||
) {
|
||||
/** `sha256:<hex>`,与 [Fingerprint] 的格式保持一致。 */
|
||||
val fingerprint: String = fingerprintOf(certificate)
|
||||
|
||||
companion object {
|
||||
private const val TAG = "TlsIdentity"
|
||||
private const val CERT_FILE = "ttstd_tls_cert.pem"
|
||||
private const val KEY_FILE = "ttstd_tls_key.pem"
|
||||
private const val BEGIN_CERT = "-----BEGIN CERTIFICATE-----"
|
||||
private const val END_CERT = "-----END CERTIFICATE-----"
|
||||
private const val BEGIN_KEY = "-----BEGIN PRIVATE KEY-----"
|
||||
private const val END_KEY = "-----END PRIVATE KEY-----"
|
||||
|
||||
@Volatile
|
||||
private var cached: TlsIdentity? = null
|
||||
|
||||
/** 取本机 TLS 身份;生成失败返回 null(此时控制通道退回明文)。 */
|
||||
fun of(context: Context): TlsIdentity? {
|
||||
cached?.let { return it }
|
||||
synchronized(this) {
|
||||
cached?.let { return it }
|
||||
val dir = context.filesDir
|
||||
val identity = runCatching { load(dir) ?: generate(dir) }
|
||||
.onFailure { Log.w(TAG, "TLS 身份不可用,控制通道将不加密", it) }
|
||||
.getOrNull()
|
||||
cached = identity
|
||||
return identity
|
||||
}
|
||||
}
|
||||
|
||||
fun fingerprintOrEmpty(context: Context): String = of(context)?.fingerprint ?: ""
|
||||
|
||||
fun fingerprintOf(certificate: X509Certificate): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256").digest(certificate.encoded)
|
||||
return "sha256:" + digest.joinToString("") { byte -> "%02x".format(byte) }
|
||||
}
|
||||
|
||||
private fun load(dir: File): TlsIdentity? {
|
||||
val certFile = File(dir, CERT_FILE)
|
||||
val keyFile = File(dir, KEY_FILE)
|
||||
if (!certFile.exists() || !keyFile.exists()) return null
|
||||
val certificate = CertificateFactory.getInstance("X.509")
|
||||
.generateCertificate(certFile.inputStream()) as? X509Certificate ?: return null
|
||||
val keyBytes = pemBody(keyFile.readText(), BEGIN_KEY, END_KEY) ?: return null
|
||||
val privateKey = KeyFactory.getInstance(certificate.publicKey.algorithm)
|
||||
.generatePrivate(PKCS8EncodedKeySpec(Base64.decode(keyBytes, Base64.DEFAULT)))
|
||||
return TlsIdentity(certificate, privateKey)
|
||||
}
|
||||
|
||||
private fun generate(dir: File): TlsIdentity {
|
||||
val generator = KeyPairGenerator.getInstance("EC").apply {
|
||||
initialize(ECGenParameterSpec("secp256r1"), SecureRandom())
|
||||
}
|
||||
val pair = generator.generateKeyPair()
|
||||
val now = System.currentTimeMillis()
|
||||
val name = org.bouncycastle.asn1.x500.X500Name("CN=TTSTD Receiver")
|
||||
val builder = JcaX509v3CertificateBuilder(
|
||||
name,
|
||||
BigInteger(64, SecureRandom()).abs(),
|
||||
Date(now - 86_400_000L),
|
||||
Date(now + 10L * 365 * 86_400_000L),
|
||||
name,
|
||||
pair.public,
|
||||
)
|
||||
val signer = JcaContentSignerBuilder("SHA256withECDSA").build(pair.private)
|
||||
val certificate = JcaX509CertificateConverter().getCertificate(builder.build(signer))
|
||||
|
||||
File(dir, CERT_FILE).writeText(pem(certificate.encoded, BEGIN_CERT, END_CERT))
|
||||
File(dir, KEY_FILE).writeText(
|
||||
pem(pair.private.encoded, BEGIN_KEY, END_KEY),
|
||||
)
|
||||
Log.i(TAG, "已生成 TLS 自签证书: ${fingerprintOf(certificate)}")
|
||||
return TlsIdentity(certificate, pair.private)
|
||||
}
|
||||
|
||||
private fun pem(der: ByteArray, begin: String, end: String): String =
|
||||
"$begin\n${Base64.encodeToString(der, Base64.NO_WRAP)}\n$end\n"
|
||||
|
||||
private fun pemBody(text: String, begin: String, end: String): String? {
|
||||
val start = text.indexOf(begin)
|
||||
val stop = text.indexOf(end)
|
||||
if (start < 0 || stop <= start) return null
|
||||
return text.substring(start + begin.length, stop).replace("\r", "").replace("\n", "")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user