如何用Carlifornium实现使用PSK算法的DTLS协议,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
Carlifornium是Eclipse上的一个CoAP+DTLS框架,CoAP和DTLS是啥就先不说了,上代码。
//指定公私钥文件信息 private static final char[] KEY_STORE_PASSWORD = "123456".toCharArray(); private static final String KEY_STORE_LOCATION = "demo2.jks"; private static final char[] TRUST_STORE_PASSWORD = "123456".toCharArray(); private static final String TRUST_STORE_LOCATION = "demo2.jks"; ...... //加载公私钥文件 SslContextUtil.Credentials clientCredentials = SslContextUtil.loadCredentials( SslContextUtil.CLASSPATH_SCHEME + KEY_STORE_LOCATION, "demo2", KEY_STORE_PASSWORD,KEY_STORE_PASSWORD); Certificate[] trustedCertificates = SslContextUtil.loadTrustedCertificates(SslContextUtil.CLASSPATH_SCHEME + TRUST_STORE_LOCATION, "demo2", TRUST_STORE_PASSWORD); DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(); //指定PSK密钥 builder.setPskStore(new StaticPskStore("Client_identity", "secretPSK".getBytes())); builder.setIdentity(clientCredentials.getPrivateKey(), clientCredentials.getCertificateChain(),CertificateType.RAW_PUBLIC_KEY, CertificateType.X_509); builder.setTrustStore(trustedCertificates); builder.setRpkTrustAll(); builder.setConnectionThreadCount(1); dtlsConnector = new DTLSConnector(builder.build());
这里的demo2.jks,是用jdk的keytool生成的,我是偷懒了,用的同样的公私钥,KEY_STORE_LOCATION 应该是自己的密钥
keytool -genkey -alias demo2 -keypass 123456 -keyalg EC -keysize 256 -validity 3650 -keystore demo2.jks -storepass 123456
keytool生成的pass要与代码中的password一致, alias的名称也要一致。
客户端代码
DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(); //指定PSK的密钥,字符串secretPSK就是密钥 builder.setPskStore(new StaticPskStore("Client_identity", "secretPSK".getBytes())); builder.setConnectionThreadCount(1); //指定用PSK密钥,不然会自动查找ECDHE的公私钥 builder.setSupportedCipherSuites("TLS_PSK_WITH_AES_128_GCM_SHA256"); dtlsConnector = new DTLSConnector(builder.build());
交互过程抓包大约是这样:
在Server Hello 里能看到使用的是我们指定的PSK算法。
如果两边的配置密钥错误,能看到数据失败:
pom.xml中的依赖如下
<dependencies> <dependency> <groupId>org.eclipse.californium</groupId> <artifactId>californium-core</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>org.eclipse.californium</groupId> <artifactId>scandium</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.30</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.13.3</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.13.3</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.13.3</version> </dependency> </dependencies>
看完上述内容,你们掌握如何用Carlifornium实现使用PSK算法的DTLS协议的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
原创文章,作者:kepupublish,如若转载,请注明出处:https://blog.ytso.com/tech/opensource/219789.html