当前位置: 首页 > 工具软件 > Californium > 使用案例 >

import org.eclipse.californium.scandium.DTLSConnector;

郗欣嘉
2023-12-01

DTLS 服务器样例代码

/*******************************************************************************
 * Copyright (c) 2015 Institute for Pervasive Computing, ETH Zurich and others.
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 * 
 * The Eclipse Public License is available at
 *    http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 *    http://www.eclipse.org/org/documents/edl-v10.html.
 * 
 * Contributors:
 *    Matthias Kovatsch - creator and main architect
 *    Stefan Jucker - DTLS implementation
 ******************************************************************************/
package org.eclipse.californium.scandium.examples;
 
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.logging.Level;
import java.util.logging.Logger;
 
import org.eclipse.californium.elements.Connector;
import org.eclipse.californium.elements.RawData;
import org.eclipse.californium.elements.RawDataChannel;
import org.eclipse.californium.scandium.DTLSConnector;
import org.eclipse.californium.scandium.ScandiumLogger;
import org.eclipse.californium.scandium.config.DtlsConnectorConfig;
import org.eclipse.californium.scandium.dtls.pskstore.InMemoryPskStore;
 
public class ExampleDTLSServer {
 
    static {
        ScandiumLogger.initialize();
        ScandiumLogger.setLevel(Level.FINE);
    }
 
    private static final int DEFAULT_PORT = 5684; 
    private static final Logger LOG = Logger.getLogger(ExampleDTLSServer.class.getName());
    private static final String TRUST_STORE_PASSWORD = "rootPass";
    private static final String KEY_STORE_PASSWORD = "endPass";
    private static final String KEY_STORE_LOCATION = "../certs/keyStore.jks";
    private static final String TRUST_STORE_LOCATION = "../certs/trustStore.jks";
 
    private DTLSConnector dtlsConnector;
 
    public ExampleDTLSServer() {
        InMemoryPskStore pskStore = new InMemoryPskStore();
        // put in the PSK store the default identity/psk for tinydtls tests
        pskStore.setKey("Client_identity", "secretPSK".getBytes());
        InputStream in = null;
        try {
            // load the key store
            KeyStore keyStore = KeyStore.getInstance("JKS");
            in = new FileInputStream(KEY_STORE_LOCATION);
            keyStore.load(in, KEY_STORE_PASSWORD.toCharArray());
 
            // load the trust store
            KeyStore trustStore = KeyStore.getInstance("JKS");
            InputStream inTrust = new FileInputStream(TRUST_STORE_LOCATION);
            trustStore.load(inTrust, TRUST_STORE_PASSWORD.toCharArray());
 
            // You can load multiple certificates if needed
            Certificate[] trustedCertificates = new Certificate[1];
            trustedCertificates[0] = trustStore.getCertificate("root");
 
            DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(new InetSocketAddress(DEFAULT_PORT));
            builder.setPskStore(pskStore);
            builder.setIdentity((PrivateKey)keyStore.getKey("server", KEY_STORE_PASSWORD.toCharArray()),
                    keyStore.getCertificateChain("server"), true);
            builder.setTrustStore(trustedCertificates);
            dtlsConnector = new DTLSConnector(builder.build(), null);
            dtlsConnector.setRawDataReceiver(new RawDataChannelImpl(dtlsConnector));
 
        } catch (GeneralSecurityException | IOException e) {
            LOG.log(Level.SEVERE, "Could not load the keystore", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    LOG.log(Level.SEVERE, "Cannot close key store file", e);
                }
            }
        }
 
    }
 
    public void start() {
        try {
            dtlsConnector.start();
        } catch (IOException e) {
            throw new IllegalStateException("Unexpected error starting the DTLS UDP server",e);
        }
    }
 
    private class RawDataChannelImpl implements RawDataChannel {
 
        private Connector connector;
 
        public RawDataChannelImpl(Connector con) {
            this.connector = con;
        }
 
        @Override
        public void receiveData(final RawData raw) {
            LOG.log(Level.INFO, "Received request: {0}", new String(raw.getBytes()));
            connector.send(new RawData("ACK".getBytes(), raw.getAddress(), raw.getPort()));
        }
    }
 
    public static void main(String[] args) {
 
        ExampleDTLSServer server = new ExampleDTLSServer();
        server.start();
    }
}

<?xml version='1.0' encoding='UTF-8'?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.eclipse.californium</groupId>
        <artifactId>demo-apps</artifactId>
        <version>2.0.0-SNAPSHOT</version>
    </parent>
    <artifactId>sc-dtls-example-server</artifactId>

    <name>Sc-DTLS-Example-Server</name>
    <description>Example code illustrating the usage &amp; configuration of Scandium</description>

    <properties>
        <assembly.mainClass>org.eclipse.californium.scandium.examples.ExampleDTLSServer</assembly.mainClass>
    </properties>

    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>scandium</artifactId>
        </dependency>
        
        <!-- runtime dependencies -->
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>demo-certs</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <!-- inherit configuration from parent POM -->
            </plugin>
        </plugins>
    </build>
</project>

客户端


/*******************************************************************************
 * Copyright (c) 2015 Institute for Pervasive Computing, ETH Zurich and others.
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 * 
 * The Eclipse Public License is available at
 *    http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 *    http://www.eclipse.org/org/documents/edl-v10.html.
 * 
 * Contributors:
 *    Matthias Kovatsch - creator and main architect
 *    Stefan Jucker - DTLS implementation
 ******************************************************************************/
package org.eclipse.californium.scandium.examples;
 
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
 
import org.eclipse.californium.elements.RawData;
import org.eclipse.californium.elements.RawDataChannel;
import org.eclipse.californium.scandium.DTLSConnector;
import org.eclipse.californium.scandium.ScandiumLogger;
import org.eclipse.californium.scandium.config.DtlsConnectorConfig;
import org.eclipse.californium.scandium.dtls.pskstore.StaticPskStore;
 
public class ExampleDTLSClient {
 
    static {
        ScandiumLogger.initialize();
        ScandiumLogger.setLevel(Level.FINE);
    }
 
    private static final int DEFAULT_PORT = 5684;
    private static final Logger LOG = Logger.getLogger(ExampleDTLSClient.class.getName());
    private static final String TRUST_STORE_PASSWORD = "rootPass";
    private static final String KEY_STORE_PASSWORD = "endPass";
    private static final String KEY_STORE_LOCATION = "../certs/keyStore.jks";
    private static final String TRUST_STORE_LOCATION = "../certs/trustStore.jks";
 
    private DTLSConnector dtlsConnector;
 
    public ExampleDTLSClient(final CountDownLatch latch) {
        InputStream inTrust = null;
        InputStream in = null;
        try {
            // load key store
            KeyStore keyStore = KeyStore.getInstance("JKS");
            in = new FileInputStream(KEY_STORE_LOCATION);
            keyStore.load(in, KEY_STORE_PASSWORD.toCharArray());
 
            // load trust store
            KeyStore trustStore = KeyStore.getInstance("JKS");
            inTrust = new FileInputStream(TRUST_STORE_LOCATION);
            trustStore.load(inTrust, TRUST_STORE_PASSWORD.toCharArray());
 
            // You can load multiple certificates if needed
            Certificate[] trustedCertificates = new Certificate[1];
            trustedCertificates[0] = trustStore.getCertificate("root");
 
            DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(new InetSocketAddress(0));
            builder.setPskStore(new StaticPskStore("Client_identity", "secretPSK".getBytes()));
            builder.setIdentity((PrivateKey)keyStore.getKey("client", KEY_STORE_PASSWORD.toCharArray()),
                    keyStore.getCertificateChain("client"), true);
            builder.setTrustStore(trustedCertificates);
            dtlsConnector = new DTLSConnector(builder.build(), null);
            dtlsConnector.setRawDataReceiver(new RawDataChannel() {
                
                @Override
                public void receiveData(RawData raw) {
                    LOG.log(Level.INFO, "Received response: {0}", new String(raw.getBytes()));
                    latch.countDown();
                    dtlsConnector.destroy();
                }
            });
 
        } catch (GeneralSecurityException | IOException e) {
            LOG.log(Level.SEVERE, "Could not load the keystore", e);
        } finally {
            try {
                if (inTrust != null) {
                    inTrust.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                LOG.log(Level.SEVERE, "Cannot close key store file", e);
            }
        }
    }
 
    private void test(InetSocketAddress peer) {
        try {
            dtlsConnector.start();
            dtlsConnector.send(new RawData("HELLO WORLD".getBytes(), peer));
        } catch (IOException e) {
            LOG.log(Level.SEVERE, "Cannot send message", e);
        }
    }
 
    public static void main(String[] args) throws InterruptedException {
 
        final CountDownLatch latch = new CountDownLatch(1);
        ExampleDTLSClient client = new ExampleDTLSClient(latch);
        InetSocketAddress peer = new InetSocketAddress("localhost", DEFAULT_PORT);
        if (args.length == 2) {
            peer = new InetSocketAddress(args[0], Integer.parseInt(args[1]));
        }
        client.test(peer);
        latch.await(5, TimeUnit.SECONDS);
    }
}
 类似资料:

相关阅读

相关文章

相关问答