- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我在使用SSL套接字建立客户端服务器套接字连接时遇到问题。我仍在学习SSL加密以及处理证书和 keystore 的过程。我有一个客户端和服务器应用程序,它们应该按如下方式相互连接:
服务器-SSLReverseEchoer.java
import java.io.*;
import java.net.*;
import java.security.*;
import javax.net.ssl.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class SSLReverseEchoer {
public static void main(String[] args) {
String ksName = "sslkeystore.jks";
String keystorePass = "sslkeystorepassword";
char ksPass[] = keystorePass.toCharArray();
int sslPort = 9099;
Security.addProvider(new BouncyCastleProvider());
File file = new File(ksName);
String absPath = file.getAbsolutePath();
System.setProperty("javax.net.ssl.keyStore", absPath);
System.setProperty("javax.net.ssl.keyStorePassword", "sslkeystorepassword");
try {
//Get keystore w/ password
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(ksName), ksPass);
//Trust Manager
TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, ksPass);
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
SSLServerSocketFactory ssf = sc.getServerSocketFactory();
SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(sslPort);
printServerSocketInfo(s);
//WAIT FOR CONNECTION TODO ADD THREAD for NIO
SSLSocket c = (SSLSocket) s.accept();
printSocketInfo(c);
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(
c.getOutputStream()));
BufferedReader r = new BufferedReader(new InputStreamReader(
c.getInputStream()));
String m = "Welcome to SSL Reverse Echo Server."+
" Please type in some words.";
w.write(m,0,m.length());
w.newLine();
w.flush();
while ((m=r.readLine())!= null) {
if (m.equals(".")) break;
char[] a = m.toCharArray();
int n = a.length;
for (int i=0; i<n/2; i++) {
char t = a[i];
a[i] = a[n-1-i];
a[n-i-1] = t;
}
w.write(a,0,n);
w.newLine();
w.flush();
}
w.close();
r.close();
c.close();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printSocketInfo(SSLSocket s) {
System.out.println("Socket class: "+s.getClass());
System.out.println(" Remote address = "
+s.getInetAddress().toString());
System.out.println(" Remote port = "+s.getPort());
System.out.println(" Local socket address = "
+s.getLocalSocketAddress().toString());
System.out.println(" Local address = "
+s.getLocalAddress().toString());
System.out.println(" Local port = "+s.getLocalPort());
System.out.println(" Need client authentication = "
+s.getNeedClientAuth());
SSLSession ss = s.getSession();
System.out.println(" Cipher suite = "+ss.getCipherSuite());
System.out.println(" Protocol = "+ss.getProtocol());
}
private static void printServerSocketInfo(SSLServerSocket s) {
System.out.println("Server socket class: "+s.getClass());
System.out.println(" Socket address = "
+s.getInetAddress().toString());
System.out.println(" Socket port = "
+s.getLocalPort());
System.out.println(" Need client authentication = "
+s.getNeedClientAuth());
System.out.println(" Want client authentication = "
+s.getWantClientAuth());
System.out.println(" Use client mode = "
+s.getUseClientMode());
}
}
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class SSLSocketClient {
public static void main(String[] args) {
int sslPort = 9099;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintStream out = System.out;
SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault();
try {
SSLSocket c = (SSLSocket) f.createSocket("localhost", sslPort);
printSocketInfo(c);
c.startHandshake();
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()));
String m = null;
while ((m=r.readLine())!= null) {
out.println(m);
m = in.readLine();
w.write(m,0,m.length());
w.newLine();
w.flush();
}
w.close();
r.close();
c.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void printSocketInfo(SSLSocket s) {
System.out.println("Socket class: "+s.getClass());
System.out.println(" Remote address = "
+s.getInetAddress().toString());
System.out.println(" Remote port = "+s.getPort());
System.out.println(" Local socket address = "
+s.getLocalSocketAddress().toString());
System.out.println(" Local address = "
+s.getLocalAddress().toString());
System.out.println(" Local port = "+s.getLocalPort());
System.out.println(" Need client authentication = "
+s.getNeedClientAuth());
SSLSession ss = s.getSession();
System.out.println(" Cipher suite = "+ss.getCipherSuite());
System.out.println(" Protocol = "+ss.getProtocol());
}
}
Server socket class: class sun.security.ssl.SSLServerSocketImpl
Socket address = 0.0.0.0/0.0.0.0
Socket port = 9099
Need client authentication = false
Want client authentication = false
Use client mode = false
Socket class: class sun.security.ssl.SSLSocketImpl
Remote address = /127.0.0.1
Remote port = 62145
Local socket address = /127.0.0.1:9099
Local address = /127.0.0.1
Local port = 9099
Need client authentication = false
Cipher suite = SSL_NULL_WITH_NULL_NULL
Protocol = NONE
javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
at sun.security.ssl.SSLSocketImpl.checkEOF(SSLSocketImpl.java:1541)
at sun.security.ssl.SSLSocketImpl.checkWrite(SSLSocketImpl.java:1553)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:71)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:295)
at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141)
at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
at java.io.BufferedWriter.flush(BufferedWriter.java:254)
at com.example.SSLReverseEchoer.main(SSLReverseEchoer.java:60)
Caused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.Alerts.getSSLException(Alerts.java:154)
at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:2023)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1125)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
at sun.security.ssl.SSLSocketImpl.getSession(SSLSocketImpl.java:2267)
at com.example.SSLReverseEchoer.printSocketInfo(SSLReverseEchoer.java:94)
at com.example.SSLReverseEchoer.main(SSLReverseEchoer.java:49)
Socket class: class sun.security.ssl.SSLSocketImpl
Remote address = localhost/127.0.0.1
Remote port = 9099
Local socket address = /127.0.0.1:62145
Local address = /127.0.0.1
Local port = 62145
Need client authentication = false
Cipher suite = SSL_NULL_WITH_NULL_NULL
Protocol = NONE
javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.SSLSocketImpl.checkEOF(SSLSocketImpl.java:1541)
at sun.security.ssl.SSLSocketImpl.checkWrite(SSLSocketImpl.java:1553)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1399)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
at com.example.SSLSocketClient.main(SSLSocketClient.java:23)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
at sun.security.ssl.SSLSocketImpl.getSession(SSLSocketImpl.java:2267)
at com.example.SSLSocketClient.printSocketInfo(SSLSocketClient.java:55)
at com.example.SSLSocketClient.main(SSLSocketClient.java:22)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
... 9 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 15 more
keytool -genkey -keyalg RSA -alias sslsocket -keystore sslkeystore.jks -storepass sslkeystorepassword -validity 365 -keysize 2048
What is your first and last name?
[Unknown]: Gandalf
What is the name of your organizational unit?
[Unknown]: Wizardry
What is the name of your organization?
[Unknown]: Arnock
What is the name of your City or Locality?
[Unknown]: Minas Tirith
What is the name of your State or Province?
[Unknown]: Gondor
What is the two-letter country code for this unit?
[Unknown]: GD
Is CN=Gandalf, OU=Wizardry, O=Arnock, L=Minas Tirith, ST=Gondor, C=GD correct?
[no]: yes
Enter key password for <sslsocket>
(RETURN if same as keystore password):
keytool -export -alias sslsocket -keystore sslkeystore.jks -rfc -file X509_certificate.cer
Enter keystore password:
Certificate stored in file <X509_certificate.cer>
最佳答案
您已经倒退了。 As the Wikipedia article begins:
Public-key cryptography, or asymmetric cryptography, is any cryptographic system that uses pairs of keys: public keys that may be disseminated widely [which are mathematically] paired with private keys which are known only to the owner.
The binding between a public key and its "owner" must be correct, or else the algorithm may function perfectly and yet be entirely insecure in practice. [...] Associating a public key with its owner is typically done by protocols implementing a public key infrastructure – these allow the validity of the association to be formally verified by reference to a trusted third party in the form of either a hierarchical certificate authority (e.g., X.509) [...]
keytool -genkeypair
或过时的同义词-genkey
在文件(默认为JKS文件)中创建带有自签名(默认)证书keytool -exportcert
(或-export
)将证书(包含公钥和名称)复制到文件中,在此处将其命名为X509_certficate.cer
。由于您没有获得真正的CA证书,因此这是自签名证书,您需要将其放入每个客户端的信任库中。 keytool -importcert
将证书放入 keystore 文件(通常为JKS)中,将该 keystore 读取到内存中,并使用它来初始化TrustManager
,然后是SSLContext
,然后是SSLSocketFactory
。除了没有KeyManager
部分,这与服务器代码相似,并且您使用SSLSocket
类而不是SSLServerSocket
类。 CertificateFactory
类型的X.509
从文件中读取(仅)证书,在内存中创建 keystore (无 keystore 文件)并将证书放入其中,然后按照显式1进行。javax.net.ssl.trustStore
和...trustStorePassword
(如果不是默认的JKS,则设置为...trustStoreType
,如果不是默认的JKS,或者在Java8中也为PKCS12)以指向它。您可以通过调用System.setProperty
或在启动-Dname=value
时在命令行上使用标志java
来设置系统属性。 JREHOME/lib/security/cacerts
(或jssecacerts
(如果存在),但默认情况下不存在),并且安装为包含约一百个知名CA。这会影响使用该JRE的所有程序,除非它们使用上述选项设置了自己的信任库,这可能会或可能不会成为问题,这取决于您或其他人(在Java中)在此系统上运行的是什么。 keytool
提示输入first and last name
时实际设置的字段(回读中注意CN=Gandalf
,CN表示CommonName),应该是服务器的主机名,或更确切地说是服务器的主机名客户端使用的名称
连接到服务器(在您的示例中显然是localhost
)。另外,特别是对于Real-CA证书,可以使用名为SubjectAlternativeName(缩写为SAN)的扩展名,但是使用keytool
进行SAN相当笨拙。SSLSocket
逻辑不会(当前)验证主机名,但是大多数其他客户端(例如Web浏览器)(甚至Java中的HttpsURLConnection
)都可以验证主机名,并且除非您的服务器可以作为Gandalf
连接(没有任何域限定),否则这些客户端将拒绝即使证书本身是“有效的”,也可以使用证书连接到服务器。
关于java - SSL套接字帮助-javax.net.ssl.SSLHandshakeException : Received fatal alert: certificate_unknown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40028065/
我正在维护一些 Java 代码,我目前正在将它们转换为 C#。 Java 代码是这样做的: sendString(somedata + '\000'); 在 C# 中,我正在尝试做同样的事情: sen
如何确定函数中传递的参数是字符串还是字符(不确定如何正确调用它)文字? 我的函数(不正确): void check(const char* str) { // some code here }
我真的不知道如何准确地提出这个问题,但我希望标题已经说明了这一点。 我正在寻找一种方法(一个框架/库),它提供了执行 String.contains() 函数的能力,该函数告诉我给定的字符串是否与搜索
我正在尝试编写一些读取 Lambda 表达式并输出 beta 缩减版本的东西。 Lambda 的类型如下:\variable -> expression,应用程序的形式为 (表达式) (表达式)。因此
StackOverflow 上的第 1 篇文章,如果我没能把它做好,我深表歉意。我陷入了一个愚蠢的练习,我需要制作一个“刽子手游戏”,我尝试从“.txt”文件中读取单词,然后我得到了我的加密函数,它将
我想在 Groovy 中测试我的 Java 自定义注释,但由于字符问题而未能成功。 Groovyc: Expected 'a' to be an inline constant of type cha
当我尝试在单击按钮期间运行 javascript location.href 时,出现以下错误“字 rune 字中的字符过多”。 最佳答案 这应该使用 OnClientClick相反? 您可能还想停
我想要类似的东西: let a = ["v".utf8[0], 1, 2] 我想到的最接近的是: let a = [0x76, 1, 2] 和 "v".data(using: String.Encod
有没有办法在 MySQL 中指定 Unicode 字 rune 字? 我想用 Ascii 字符替换 Unicode 字符,如下所示: Update MyTbl Set MyFld = Replace(
阅读 PNG 规范后,我有点惊讶。我读过字 rune 字应该用像 0x41 这样的二进制值进行硬编码,而不是在(程序员友好的)'A' 中。问题似乎是在具有不同底层字符集的不同系统上编译期间字 rune
考虑一个具有 UTF-8 执行字符集的 C++11 编译器(并且符合要求 char 类型为有符号 8 位字节的 x86-64 ABI) . 字母 Ä(元音变音)具有 0xC4 的 unicode 代码
为什么即使有 UTF-8 字符串文字,C11 或 C++11 中也没有 UTF-8 字 rune 字?我知道,一般来说,字 rune 字表示单个 ASCII 字符,它与单字节 UTF-8 代码点相同,
我怎样才能用 Jade 做到这一点? how would I do this 我几乎可以做任何事情,除了引入一个 span 中间句子。 最佳答案 h3.blur. how would I do t
这似乎是一个非常简单的问题,但我只是想澄清我的疑问。我正在查看其他开发人员编写的代码。有一些涉及 float 的计算。 示例:Float fNotAvlbl = new Float(-99); 他为什
我想知道第 3 行“if dec:”中的“dec”是什么意思 1 def dec2bin(dec): 2 result='' 3 if dec:
我试图在字符串中查找不包含任何“a”字符的单词。我写了下面的代码,但它不起作用。我怎么能对正则表达式说“不包括”?我不能用“^”符号表示“不是”吗? import re string2 = "asfd
这个问题在这里已经有了答案: Is floating point math broken? (31 个答案) Is floating point arbitrary precision availa
我正在创建一个时尚的文本应用程序,但在某些地方出现错误(“字 rune 字中的字符太多”)。我只写了一个字母,但是当我粘贴它时,它会转换成许多这样的字母:“\uD83C\uDD89”,原始字母是“🆉
我正在尝试检查用户是否在文本框中输入了一个数字值,是否接受了小数位。非常感谢任何帮助。 Private Sub textbox1_AfterUpdate() If IsNumeric(textbox1
我知道一个 Byte 是 8 位,但其他的代表什么?我正在参加一个使用摩托罗拉 68k 架构的汇编类(class),我对目前的词汇感到困惑。 最佳答案 如 operator's manual for
我是一名优秀的程序员,十分优秀!