到現在,我們已經(jīng)完成了POS平臺和前端的網(wǎng)絡(luò )集成。不過(guò),還是那句話(huà):平臺系統的網(wǎng)絡(luò )安全是至關(guān)重要的。前一篇博客里我們嘗試實(shí)現了gRPC ssl/tls網(wǎng)絡(luò )連接,但測試時(shí)用的證書(shū)如何產(chǎn)生始終沒(méi)有搞清楚?,F在akka-http開(kāi)發(fā)的ws同樣面臨HTTPS的設置和使用問(wèn)題。所以,特別抽出這篇博文討論一下數字證書(shū)的問(wèn)題。
在正式的生產(chǎn)環(huán)境里數字證書(shū)應該是由第三方公證機構CA簽發(fā)的,我們需要向CA提出申請。數字證書(shū)的申請、簽發(fā)和驗證流程如下:
1) 服務(wù)? S 向第三?方機構CA提交公鑰、組織信息、個(gè)?信息(域名)等資料提出認證申請 (不需要提供私鑰)2) CA 通過(guò)各種手段驗證申請者所提供信息的真實(shí)性,如組織是否存在、 企業(yè)是否合法,是否擁有域名的所有權等3) 如信息審核通過(guò),CA 會(huì )向申請者簽發(fā)認證文件-證書(shū)。 證書(shū)包含以下信息:申請者公鑰、申請者的組織信息和個(gè)?信息、簽發(fā)機構 CA 信息、有效時(shí)間、證書(shū)序列號等信息的明?,同時(shí)包含一個(gè)簽名的產(chǎn)?生算法:首先,使用散列函數計算出證書(shū)中公開(kāi)明文信息的信息摘要,然后, 采用 CA 的私鑰對信息摘要進(jìn)?加密,這個(gè)密?就是簽名了4) 客戶(hù)端 C 向服務(wù)器 S 發(fā)出請求時(shí),S 返回證書(shū)文件5) 客戶(hù)端 C 讀取證書(shū)中的相關(guān)的明?信息,采?相同的散列函數計算得到信息摘要, 然后,利用對應 CA 的公鑰解密簽名數據,對比證書(shū)的信息摘要,如果一致,則可以確認證書(shū)的合法性,即公鑰合法6) 客戶(hù)端 C 然后檢驗證書(shū)相關(guān)的域名信息、有效時(shí)間等信息7) 客戶(hù)端 C 應內置信任 CA 的證書(shū)信息(包含公鑰),如果 CA 不被信任,則找不到對應 CA 的證書(shū),證書(shū)也會(huì )被判定非法8) 內置 CA 對應的證書(shū)稱(chēng)為根證書(shū),頒發(fā)者和使?者相同,用 CA ??的私鑰簽名,即?簽名證書(shū)(此證書(shū)中的公鑰即為 CA 的公鑰,可以使用這個(gè)公鑰對證書(shū)的簽名進(jìn)行校驗,?需另外?份證書(shū))
服務(wù)器端在通信中建立SSL加密渠道過(guò)程如下:
1)客戶(hù)端 C 發(fā)送請求到服務(wù)器端 S2) 服務(wù)器端 S 返回證書(shū)和公開(kāi)密鑰到 C,公開(kāi)密鑰作為證書(shū)的一部分傳送3)客戶(hù)端 C 檢驗證書(shū)和公開(kāi)密鑰的有效性,如果有效,則?成共享密鑰并使?公開(kāi)密鑰加密發(fā)送到服務(wù)器端 S4) 服務(wù)器端 S 使?私有密鑰解密數據,并用收到的共享密鑰加密數據,發(fā)送到客戶(hù)端 C 5) 客戶(hù)端 C 使?用共享密鑰解密數據6) SSL 加密通信渠道建立 ...
應該說(shuō),需要在客戶(hù)端進(jìn)行認證的應用場(chǎng)景不多。這種情況需要在客戶(hù)端存放數字證書(shū)。像支付寶和一些銀行客戶(hù)端一般都需要安裝證書(shū)。
好了,還是回到如何產(chǎn)生自簽名證書(shū)示范吧。下面是一個(gè)標準的用openssl命令產(chǎn)生自簽名證書(shū)流程:
在產(chǎn)生證書(shū)和密鑰的過(guò)程中所有系統提問(wèn)回答要一致。我們先假設密碼統一為:123456
1、生成根證書(shū)私鑰: rootCA.key: openssl genrsa -des3 -out rootCA.key 2048
2、根證書(shū)申請 rootCA.csr:openssl req -new -key rootCA.key -out rootCA.csr
3、用申請rootCA.csr生成根證書(shū) rootCA.crt:openssl x509 -req -days 365 -sha256 -extensions v3_ca -signkey rootCA.key -in rootCA.csr -out rootCA.crt
4、pem根證書(shū) rootCA.pem:openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem
5、創(chuàng )建?個(gè)v3.ext?件,目的是產(chǎn)生X509 v3證書(shū),主要目的是指定subjectAltName選項:
authorityKeyIdentifier=keyid,issuer basicConstraints=CA:FALSE keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment subjectAltName = @alt_names [alt_names] DNS.1 = localhost IP.1 = "192.168.11.189" IP.5 = "192.168.0.189" IP.2 = "132.232.229.60" IP.3 = "118.24.165.225" IP.4 = "129.28.108.238"
注意subjectAltName,這些都是可以信任的域名或地址。
6、構建證書(shū)密鑰 server.key:openssl req -new -sha256 -nodes -out server.csr -newkey rsa:2048 -keyout server.key
7、用根證書(shū)rootCA產(chǎn)生自簽證書(shū) server.crt:openssl x509 -req -in server.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out server.crt -days 500 -sha256 -extfile v3.ext
上面這個(gè)過(guò)程需要不斷重復回答同樣的問(wèn)題,很煩??梢杂门渲梦募?lái)一次性產(chǎn)生:
先構建一個(gè)ssl.cnf文件:
[req] prompt = no default_bits = 4096 default_md = sha256 distinguished_name = dn x509_extensions = v3_req [dn] C=CN ST=GuangDong L=ShenZhen O=Bayakala OU=POS CN=www.bayakala.com emailAddress=admin@localhost [v3_req] keyUsage=keyEncipherment, dataEncipherment extendedKeyUsage=serverAuth subjectAltName=@alt_names [alt_names] DNS.1 = localhost IP.1 = "192.168.11.189" IP.5 = "192.168.0.189" IP.2 = "132.232.229.60" IP.3 = "118.24.165.225" IP.4 = "129.28.108.238"
然后:openssl req -new -newkey rsa:2048 -sha1 -days 3650 -nodes -x509 -keyout server.key -out server.crt -config ssl.cnf
一個(gè)指令同時(shí)產(chǎn)生需要的server.crt,server.key。
除aubjectAltName外還要關(guān)注CN這個(gè)字段,它就是我們經(jīng)常會(huì )遇到系統提問(wèn):你確定信任“域名”嗎?中這個(gè)域名,也就是對外界開(kāi)放的一個(gè)使用了數字證書(shū)的域名。
把crt,key抄寫(xiě)到main/resources目錄下,然后在gRPC服務(wù)器配置證書(shū):
trait gRPCServer { val serverCrtFile = new File(getClass.getClassLoader.getResource("server.crt").getPath) val serverKeyFile = new File(getClass.getClassLoader.getResource("server.key").getPath) def runServer(service: ServerServiceDefinition): Unit = { val server = NettyServerBuilder .forPort(50051) .addService(service) .useTransportSecurity(serverCrtFile,serverKeyFile) .build .start // make sure our server is stopped when jvm is shut down Runtime.getRuntime.addShutdownHook(new Thread() { override def run(): Unit = { server.shutdown() server.awaitTermination() } }) }}啟動(dòng)gRPC服務(wù),運作正常。在看看客戶(hù)端代碼:
val clientCrtFile = new File(getClass.getClassLoader.getResource("server.crt").getPath) //或者 val clientCrtFile = new File(getClass.getClassLoader.getResource("rootCA.pem").getPath)//這樣也行 val clientCrtFile: InputStream = getClass.getClassLoader.getResourceAsStream("rootCA.pem") val sslContextBuilder = GrpcSslContexts.forClient().trustManager(clientCrtFile) //build connection channel val channel = NettyChannelBuilder .forAddress("192.168.11.189",50051) .negotiationType(NegotiationType.TLS) .sslContext(sslContextBuilder.build())// .overrideAuthority("192.168.1.3") .build()測試連接,gRPC SSL/TLS成功!
現在開(kāi)始了解一下https證書(shū)的配置使用方法吧??戳艘幌耡kka-http關(guān)于server端HTTPS設置的例子,證書(shū)是嵌在HttpsConnectionContext類(lèi)型里面的。還有就是akka-http使用的https證書(shū)格式只支持pkcs12,所以需要把上面用openssl產(chǎn)生的自簽名證書(shū)server.crt轉成server.p12。這個(gè)轉換又需要先產(chǎn)生證書(shū)鏈certificate-chain chain.pem:
1)產(chǎn)生certificate-chain: cat server.crt rootCA.crt > chain.pem
2) server.crt轉換成server.p12: openssl pkcs12 -export -name servercrt -in chain.pem -inkey server.key -out server.p12
https server 測試代碼:
//#importsimport java.io.InputStreamimport java.security.{ SecureRandom, KeyStore }import javax.net.ssl.{ SSLContext, TrustManagerFactory, KeyManagerFactory }import akka.actor.ActorSystemimport akka.http.scaladsl.server.{ Route, Directives }import akka.http.scaladsl.{ ConnectionContext, HttpsConnectionContext, Http }import akka.stream.ActorMaterializerimport akka.http.scaladsl.Httpimport akka.http.scaladsl.server.Directives._//#importsobject HttpsDemo extends App { implicit val httpSys = ActorSystem("httpSystem") implicit val httpMat = ActorMaterializer() implicit val httpEC = httpSys.dispatcher val password: Array[Char] = "123456".toCharArray // do not store passwords in code, read them from somewhere safe! val ks: KeyStore = KeyStore.getInstance("PKCS12") val keystore: InputStream = getClass.getClassLoader.getResourceAsStream("server.p12") ks.load(keystore, password) val keyManagerFactory: KeyManagerFactory = KeyManagerFactory.getInstance("SunX509") keyManagerFactory.init(ks, password) val tmf: TrustManagerFactory = TrustManagerFactory.getInstance("SunX509") tmf.init(ks) val sslContext: SSLContext = SSLContext.getInstance("TLS") sslContext.init(keyManagerFactory.getKeyManagers, tmf.getTrustManagers, new SecureRandom) val https: HttpsConnectionContext = ConnectionContext.https(sslContext) val route = get { complete("Hello world!") } val (port, host) = (50081,"192.168.11.189") val bindingFuture = Http().bindAndHandle(route,host,port,connectionContext = https) println(s"Https Server running at $host $port. Press any key to exit ...") scala.io.StdIn.readLine() bindingFuture.flatMap(_.unbind()) .onComplete(_ => httpSys.terminate())}用safari連接https://192.168.11.189:50081/, 彈出窗口一堆廢話(huà)后還是成功連接上了。
聯(lián)系客服