MongoDB使用x.509證書認證

文章目錄

  • 自定義證書
    • 生成CA證書
    • 生成服務器之間的證書
    • 生成集群證書
    • 生成用戶證書
  • MongoDB配置
  • java使用x.509證書連接MongoDB
  • MongoShell使用證書連接

8.0版本的mongodb開啟復制集,配置證書認證

自定義證書

生成CA證書

生成ca私鑰: openssl genrsa -out ca.key 4096 # 生成RSA 4096位私鑰
生成ca證書: openssl req -x509 -new -nodes -key ca.key -sha256 -days 3650 -out ca.crt -subj "/CN=MongoDB Root CA/O=MyOrg/OU=Security"
驗證ca證書: openssl x509 -in ca.crt -text -noout
生成pkcs12格式的p12文件:后續用于java代碼認證
cat ca.crt ca.key > ca.pem
openssl pkcs12 -export -in ca.pem -out ca.p12 -password pass:123456

生成服務器之間的證書

生成服務器私鑰: openssl genrsa -out server.key 2048
生成證書簽名請求: openssl req -new -key server.key -out server.csr -subj "/CN=1.1.1.1/O=MyOrg/OU=Servers"
生成擴展配置文件(server.ext):

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage=digitalSignature, keyEncipherment
extendedKeyUsage=serverAuth
subjectAltName=DNS:mongodb-server.example.com,DNS:localhost,IP:192.168.1.100

用ca簽發證書: openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365 -sha256 -extfile server.ext
合并證書與私鑰: cat server.crt server.key > server.pem
驗證服務器證書: openssl verify -CAfile ca.crt server.crt # 應顯示 “OK”

生成集群證書

生成集群私鑰: openssl genrsa -out cluster.key 2048
生成CSR : openssl req -new -key cluster.key -out cluster.csr -subj "/CN=node1/O=MyOrg/OU=MongoDB-Cluster" 必須包含一致的 O(組織)或 OU(部門),否則集群節點無法相互認證。
生成擴展配置文件(cluster.ext):

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage=digitalSignature, keyEncipherment
extendedKeyUsage=clientAuth

ca簽發集群證書: openssl x509 -req -in cluster.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out cluster.crt -days 365 -sha256 -extfile cluster.ext
合并證書與私鑰: cat cluster.crt cluster.key > cluster.pem
驗證集群證書:
openssl x509 -in cluster.crt -text | grep "Subject:" # 確認O/OU一致性
openssl verify -CAfile ca.crt cluster.crt # 應顯示 “OK”

生成用戶證書

生成用戶私鑰: openssl genrsa -out zy1.key 2048
生成CSR : openssl req -new -key zy1.key -out zy1.csr -subj "/O=MyOrg/CN=zy1" 必須包含一致的 O(組織)或 OU(部門),否則集群節點無法相互認證。
生成擴展配置文件( zy1.ext):

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage=digitalSignature, keyEncipherment
extendedKeyUsage=clientAuth

ca簽發集群證書: openssl x509 -req -in zy1.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out zy1.crt -days 365 -sha256 -extfile zy1.ext
合并證書與私鑰: cat zy1.crt zy1.key > zy1.pem
獲取subject : openssl x509 -in /usr/local/database/mongodb8.0.5/crt/zy1.pem -inform PEM -subject -nameopt RFC2253

生成pkcs12 格式的信任庫文件:
openssl pkcs12 -export -inkey zy1.pem -in zy1.pem -out zy1_pem.p12 -password pass:123456
測試PKCS12密碼正確性
keytool -list -v -keystore C:\Users\Administrator\Desktop\crt\zy1_pem.p12 -storetype pkcs12

MongoDB配置

mongodb配置:

     # mongod.confnet:tls:mode: requireTLSCAFile: /path/to/ca.crtcertificateKeyFile: /path/to/server.pemclusterFile: /path/to/cluster.pemsecurity:clusterAuthMode: x509authorization: enabled	

所有pem文件的權限都設為600 : chmod 600 ca.crt server.pem cluster.pem
客戶端的證書由同一CA簽發,并且在Mongodb中創建對應用戶,如下:用戶名為O=MyOrg,CN=zy,需要與證書中的Subject保持一致。可以通過名命令獲取:
openssl x509 -in /usr/local/database/mongodb8.0.5/crt/zy1.pem -inform PEM -subject -nameopt RFC2253

db.getSiblingDB("$external").runCommand({createUser: "O=MyOrg,CN=zy",roles: [{ role: "readWrite", db: "test" },{ role: "userAdminAnyDatabase", db: "admin" }],writeConcern: { w: "majority" , wtimeout: 5000 }}
)

java使用x.509證書連接MongoDB

package com.zy.sslcontext;import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;/*** Connect to a MongoDB cluster with TLS connection.* Validate MongoDB server's certificate with the CA certificate. Present a Client certificate to be validated by* the MongoDB server.** Use X509 certificate to authenticate with the MongoDB server** Create a custom {@link javax.net.ssl.SSLContext} with the TrustStore holding the CA certificate and* the KeyStore holding the Client certificate and provide it to the MongoDB Driver.*/
public class ValidateServerPresentClientCertificateX509Auth {public static void main(String[] args) {//     System.setProperty("javax.net.debug", "ssl:handshake:verbose");// Configure MongoDB Driver to use MONGODB-X509 as authentication mechanism// 此處url可以不用填寫用戶名密碼,則后續配置時采用credential(MongoCredential.createMongoX509Credential())使用證書在的用戶信息進行數據操作String connectionString = "mongodb://zy:123456@1.1.1.1:27017/?&ssl=true"; SSLContext sslContext;try {sslContext = getSSLContext();} catch (Exception e) {System.out.println("Failed to generate SSLContext. Error: " + e.getMessage());return;}MongoClientSettings settings = MongoClientSettings.builder().applyConnectionString(new ConnectionString(connectionString)) .applyToSslSettings(builder -> {builder.enabled(true); // 開啟sslbuilder.context(sslContext);})
//                .credential(MongoCredential.createCredential("zy","admin","123456".toCharArray()))
//                .credential(MongoCredential.createMongoX509Credential("O=MyOrg,CN=zy"))
//                .credential(MongoCredential.createMongoX509Credential()).applyToConnectionPoolSettings(builder -> builder.maxSize(1)          // 總最大連接數(所有實例總和).minSize(1)           // 總最小空閑連接數.maxWaitTime(1500, TimeUnit.MILLISECONDS).maxConnectionIdleTime(10, TimeUnit.MINUTES)).applyToSocketSettings(b -> b.connectTimeout(3000, TimeUnit.MILLISECONDS).readTimeout(5000, TimeUnit.MILLISECONDS)).build();MongoClient client = MongoClients.create(settings);MongoDatabase test = client.getDatabase("test");MongoCollection<Document> coll  = test.getCollection("collection1");// Retrieve the first document and print itSystem.out.println(coll.getNamespace());System.out.println(coll.find().first());MongoCollection<Document> collection = client.getDatabase("zy").getCollection("test1");collection.find().forEach(System.out::println);}/*** Load CA certificate from the file into the Trust Store.* Use PKCS12 keystore storing the Client certificate and read it into the {@link KeyStore}* Generate {@link SSLContext} from the Trust Store and {@link KeyStore}** @return SSLContext** @throws IOException* @throws CertificateException* @throws NoSuchAlgorithmException* @throws KeyStoreException* @throws KeyManagementException*/private static SSLContext getSSLContext() throws IOException, CertificateException,NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException {//        String certsPath = System.getProperty("cert_path");String certsPath = "C:\\Users\\Administrator\\Desktop\\crt\\";// Path to the CA certificate on diskString caCertPath = certsPath + "ca.crt";// 避坑:使用JKS認證失敗// openssl pkcs12 -export -inkey zy.key -in zy.pem -out zy.p12// Path to the PKCS12 Key Store holding the Client certificateString clientCertPath = certsPath + "zy1_pem.p12";String clientCertPwd  = "123456";SSLContext sslContext;try (InputStream caInputStream = new FileInputStream(caCertPath);InputStream clientInputStream = new FileInputStream(clientCertPath)) {// Read Client certificate from PKCS12 Key StoreKeyStore clientKS = KeyStore.getInstance("PKCS12");clientKS.load(clientInputStream, clientCertPwd.toCharArray());// Retrieve Key Managers from the Client certificate Key StoreKeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());kmf.init(clientKS, clientCertPwd.toCharArray());KeyManager[] keyManagers = kmf.getKeyManagers();// Read CA certificate from file and convert it into X509CertificateCertificateFactory certFactory = CertificateFactory.getInstance("X509");X509Certificate caCert = (X509Certificate)certFactory.generateCertificate(caInputStream);KeyStore caKS = KeyStore.getInstance(KeyStore.getDefaultType());caKS.load(null);caKS.setCertificateEntry("caCert", caCert);// Initialize Trust ManagerTrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());tmf.init(caKS);// Create SSLContext. We need Trust Manager only in this use casesslContext = SSLContext.getInstance("TLS");sslContext.init(keyManagers, tmf.getTrustManagers(), null);}return sslContext;}
}

MongoShell使用證書連接

./mongosh --host 1.1.1.1 --tls --tlsCAFile /usr/local/database/mongodb8.0.5/crt/ca.crt --tlsCertificateKeyFile /usr/local/database/mongodb8.0.5/crt/zy.pem --authenticationDatabase '$external' --authenticationMechanism MONGODB-X509

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/80923.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/80923.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/80923.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Python爬蟲實戰:研究js混淆加密

一、引言 在當今數字化時代,數據已成為推動各行業發展的核心驅動力。網絡爬蟲作為一種高效的數據采集工具,能夠從互聯網上自動獲取大量有價值的信息。然而,隨著互聯網技術的不斷發展,許多網站為了保護自身數據安全和知識產權,采用了 JavaScript 混淆加密技術來防止數據被…

Java項目層級介紹 java 層級 層次

java 層級 層次 實體層 控制器層 數據連接層 Service : 業務處理類 Repository &#xff1a;數據庫訪問類 Java項目層級介紹 https://blog.csdn.net/m0_67574906/article/details/145811846 在Java項目中&#xff0c;層級結構&#xff08;Layered Architecture&#xf…

網絡安全頂會——SP 2025 論文清單與摘要

1、"Check-Before-you-Solve": Verifiable Time-lock Puzzles 時間鎖謎題是一種密碼學原語&#xff0c;它向生成者保證該謎題無法在少于T個順序計算步驟內被破解。近年來&#xff0c;該技術已在公平合約簽署和密封投標拍賣等場景中得到廣泛應用。然而&#xff0c;求解…

《100天精通Python——基礎篇 2025 第18天:正則表達式入門實戰,解鎖字符串處理的魔法力量》

目錄 一、認識正則表達式二、正則表達式基本語法2.1 行界定符2.2 單詞定界符2.3 字符類2.4 選擇符2.5 范圍符2.6 排除符2.7 限定符2.8 任意字符2.9 轉義字符2.10 反斜杠2.11 小括號2.11.1 定義獨立單元2.11.2 分組 2.12 反向引用2.13 特殊構造2.14 匹配模式 三、re模塊3.1 comp…

思邁特軟件攜手天陽科技,打造ChatBI金融智能分析新標桿

5月10日&#xff0c;廣州思邁特軟件有限公司&#xff08;以下簡稱“思邁特軟件”&#xff09;與天陽宏業科技股份有限公司&#xff08;以下簡稱“天陽科技”&#xff09;在北京正式簽署戰略合作協議。思邁特軟件董事長吳華夫、CEO姚詩成&#xff0c;天陽科技董事長兼總裁歐陽建…

OPENSSL-1.1.1的使用及注意事項

下載鏈接&#xff1a; OpenSSL1.1.1一個廣泛使用的開源加密庫資源-CSDN文庫 OpenSSL 1.1.1 是一個廣泛使用的開源加密庫&#xff0c;以下是其使用方法及注意事項&#xff1a; 使用方法 安裝&#xff1a; Linux系統&#xff1a; 從源碼編譯安裝&#xff1a;訪問 OpenSSL 官網…

數據庫優化

一、慢 SQL 排查全流程 1. 開啟慢查詢日志&#xff1a;精準定位問題 SQL 慢查詢日志是定位性能問題的首要工具&#xff0c;通過記錄執行超時或未使用索引的 SQL&#xff0c;為優化提供依據。 配置步驟&#xff1a; ① 臨時啟用&#xff08;生效至服務重啟&#xff09; sql …

GO語言-導入自定義包

文章目錄 1. 項目目錄結構2. 創建自定義包3. 初始化模塊4. 導入自定義包5. 相對路徑導入 在Go語言中導入自定義包需要遵循一定的目錄結構和導入規則。以下是詳細指南&#xff08;包含兩種方式&#xff09;&#xff1a; 1. 項目目錄結構 方法1&#xff1a;適用于Go 1.11 &#…

記錄算法筆記(2025.5.11) 二叉樹的中序遍歷

給定一個二叉樹的根節點 root &#xff0c;返回 它的 中序 遍歷 。 示例 1&#xff1a; 輸入&#xff1a;root [1,null,2,3] 輸出&#xff1a;[1,3,2] 示例 2&#xff1a; 輸入&#xff1a;root [] 輸出&#xff1a;[] 示例 3&#xff1a; 輸入&#xff1a;root [1] …

【iptables防火墻】 -- DDos防御

最近有客戶要定制路由器的默認防火墻等級&#xff0c;然后涉及到了DDos規則&#xff0c;對比客戶提供的規則發現我們現有的規則存在明顯的錯誤&#xff0c;在此記錄一下如何使用iptables防護DDoS攻擊 直接貼一下規則 #開啟TCP SYN Cookies 機制 sysctl -w net.ipv4.tcp_synco…

[Java][Leetcode simple]26. 刪除有序數組中的重復項

思路 第一個元素不動從第二個元素開始&#xff1a;只要跟上一個元素不一樣就放入數組中 public int removeDuplicates(int[] nums) {int cnt1;for(int i 1; i < nums.length; i) {if(nums[i] ! nums[i-1]) {nums[cnt] nums[i];}}return cnt;}

微服務!!

1.Nacos注冊中心 2.服務注冊 3.服務發現 4.負載均衡 5.OpenFeign 6.OpenFeign連接池 啟動程序 7.路由 8.微服務保護 1.雪崩問題 2.解決方案 1.請求限流 2.線程隔離 3.服務熔斷 3.Sentinel 1.鏈路 2.請求限流 3.線程隔離 4.Fallback 5.服務熔斷 4.分布式事務 1.Seata 2.部…

代碼隨想錄算法訓練營 Day44 動態規劃 ⅩⅠ 子序列問題

動態規劃 題目 1143. 最長公共子序列 - 力扣&#xff08;LeetCode&#xff09; 公共子序列&#xff0c;類似于最長重復子數組&#xff0c;但是不要求連續 (子序列) 1. 定義 dp&#xff0c;dp[i][j] 表示以 i-1 與 j-1 結尾的最長公共子序列的長度 2. 定義遞推公式 如果字符相…

聊一聊接口測試依賴第三方服務變更時如何處理?

目錄 一、依賴隔離與模擬 二、契約測試 三、版本控制與兼容性 四、變更監控與告警 五、容錯設計 六、自動化測試維護 七、協作機制與文檔自動化 第三方API突然改了參數或者返回結構&#xff0c;導致我們的測試用例失敗&#xff0c;這時候該怎么辦呢&#xff1f;首先想到…

Python程序,輸入IP,掃描該IP哪些端口對外是開放的,輸出端口列表

#!/usr/bin/env python # -*- coding: utf-8 -*-""" IP端口掃描程序 輸入IP地址&#xff0c;掃描該IP哪些端口對外是開放的&#xff0c;輸出端口列表 """import socket import sys import concurrent.futures import ipaddress from tabulate im…

Python----神經網絡(《Inverted Residuals and Linear Bottlenecks》論文概括和MobileNetV2網絡)

一、論文 MobileNetV2 論文提出了一種新的移動架構&#xff0c;該架構提高了移動模型在多個任務和基準測試中的性能&#xff0c;以及在各種不同模型大小范圍內的性能. 該架構基于倒殘差結構&#xff0c;其中 shortcut 連接在 thin bottleneck 層之間. 中間的 expansion 層使用輕…

Maven私服搭建與登錄全攻略

目錄 1.背景2.簡介3.安裝4.啟動總結參考文獻 1.背景 回顧下maven的構建流程&#xff0c;如果沒有私服&#xff0c;我們所需的所有jar包都需要通過maven的中央倉庫或者第三方的maven倉庫下載到本地&#xff0c;當一個公司或者一個團隊所有人都重復的從maven倉庫下載jar包&#…

EF Core 數據庫遷移命令參考

在使用 Entity Framework Core 時&#xff0c;若你希望通過 Package Manager Console (PMC) 執行遷移相關命令&#xff0c;以下是常用的 EF Core 遷移命令&#xff1a; PMC 方式 ? 常用 EF Core PMC 命令&#xff08;適用于遷移&#xff09; 操作PMC 命令添加遷移Add-Migra…

商業 |阿里云又丟出了核彈

行業翹首以盼的DeepSeek-R2沒等到&#xff0c;阿里云卻先一步丟出了核彈。 4月29日凌晨&#xff0c;阿里云正式上線了Qwen3系列模型“全家桶”&#xff0c;包含2個MoE模型、6個稠密模型。 八個模型&#xff0c;小到0.6B大到235B&#xff0c;既能在手機使用&#xff0c;也有旗…

《Python星球日記》 第66天:序列建模與語言模型

名人說:路漫漫其修遠兮,吾將上下而求索。—— 屈原《離騷》 創作者:Code_流蘇(CSDN)(一個喜歡古詩詞和編程的Coder??) 目錄 一、傳統語言模型1. n-gram 模型基礎2. n-gram 模型的局限性二、RNN 在語言建模中的應用1. 語言模型的基本原理2. RNN 構建語言模型的優勢3. 實…