Java Bouncy Castle TLS PSK example

转自:http://tiebing.blogspot.com/2013/09/java-bouncy-castle-tls-psk-example.html

Java Bouncy Castle TLS PSK example

This is an example how to use the Bouncy Castle library to write a TLS-PSK client. The server was tested with was an openssl server (openssl s_server). Keep in mind that I do not write Java program regularly, so you may find some style/usage not the best.

Source:


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.security.SecureRandom;
import java.security.Provider;
import java.security.Security;
import javax.xml.bind.DatatypeConverter;

import org.bouncycastle.asn1.x509.Certificate;
import org.bouncycastle.crypto.tls.AlertLevel;
import org.bouncycastle.crypto.tls.CipherSuite;
import org.bouncycastle.crypto.tls.DefaultTlsClient;
import org.bouncycastle.crypto.tls.ServerOnlyTlsAuthentication;
import org.bouncycastle.crypto.tls.TlsAuthentication;
import org.bouncycastle.crypto.tls.TlsClientProtocol;
import org.bouncycastle.crypto.tls.TlsPSKIdentity;
import org.bouncycastle.crypto.tls.PSKTlsClient;
import org.bouncycastle.util.io.Streams;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * A simple test designed to conduct a TLS-PSK handshake with an external TLS server.
 */
public class PSKTlsClientTest
{

 static String convertStreamToString(java.io.InputStream is) {
  java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
  return s.hasNext() ? s.next() : "";
 }

 static class Z_PSKIdentity implements TlsPSKIdentity {

  void Z_PSKIdentity(){};

  public void skipIdentityHint(){
         System.out.println("skipIdentityHint called\n");
  }

  public void notifyIdentityHint(byte[] PSK_identity_hint){
         System.out.println("notifyIdentityHint called\n");
  }

  public byte[] getPSKIdentity(){
   return "Client_identity".getBytes();
  }

  public byte[] getPSK(){
   return DatatypeConverter.parseHexBinary("1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A");
  }

 }


    public static void main(String[] args)
        throws Exception
    {

  Z_PSKIdentity pskIdentity = new Z_PSKIdentity();

        Security.addProvider(new BouncyCastleProvider());

        Socket socket = new Socket(InetAddress.getByName("192.168.1.201"), 10443);

        SecureRandom secureRandom = new SecureRandom();
        TlsClientProtocol protocol = new TlsClientProtocol(socket.getInputStream(), socket.getOutputStream(),
            secureRandom);

        MyPSKTlsClient client = new MyPSKTlsClient(pskIdentity);
        protocol.connect(client);

        OutputStream output = protocol.getOutputStream();
        output.write("GET / HTTP/1.1\r\n\r\n".getBytes("UTF-8"));

        InputStream input = protocol.getInputStream();
        System.out.println(convertStreamToString(input));

        protocol.close();
        socket.close();
    }

    static class MyPSKTlsClient
        extends PSKTlsClient
    {

  public MyPSKTlsClient(TlsPSKIdentity id){
   super(id);
  }

        public void notifyAlertRaised(short alertLevel, short alertDescription, String message, Exception cause)
        {
            PrintStream out = (alertLevel == AlertLevel.fatal) ? System.err : System.out;
            out.println("TLS client raised alert (AlertLevel." + alertLevel + ", AlertDescription." + alertDescription + ")");
            if (message != null) {
                out.println(message);
            }
            if (cause != null) {
                cause.printStackTrace(out);
            }
        }

        public void notifyAlertReceived(short alertLevel, short alertDescription)
        {
            PrintStream out = (alertLevel == AlertLevel.fatal) ? System.err : System.out;
            out.println("TLS client received alert (AlertLevel." + alertLevel + ", AlertDescription."
                + alertDescription + ")");
        }

        public TlsAuthentication getAuthentication()
            throws IOException
        {
            return new ServerOnlyTlsAuthentication()
            {
                public void notifyServerCertificate(org.bouncycastle.crypto.tls.Certificate serverCertificate)
                    throws IOException
                {
                    System.out.println("in getAuthentication");
                }
            };
        }
    }
}


The simple Makefile (I installed gnuwin32 so my system has "rm" )



all:
        javac -cp "jce-jdk13-149.jar;." PSKTlsClientTest.java
        jar -cfm tls.jar  manifest.txt PSKTlsClient*.class

run:
        run.bat -jar tls.jar
clean:
        rm -f PskTlsClient*.class PskTlsClient*.jar

The Server side. Keep in mind that openssl s_server by default uses id "Client_identity". The hint is just a hint. It does not change the fact that the serve requires the client to provide the id "Client_identity". Of course this can be changed if you make your own application. So below you can use anything for the psk_hint, or even omit the argument. 


$ cat psk_server.sh
openssl s_server \
        -psk 1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A \
        -psk_hint Client_identity\
        -cipher PSK-AES256-CBC-SHA \
        -debug -state -nocert -accept 10443 -tls1 -www

manifest.txt file


Main-Class: PSKTlsClientTest
Class-Path: . jce-jdk13-149.jar

run.bat file (The host is Windows 7)


java -cp "jce-jdk13-149.jar;." %*

POSTED BY TIEBING AT 9/13/2013

5 COMMENTS:

  1.  

    Андрей Москвичёв1/25/2014 7:21 AM

    Thanks for very useful information! 

    Do you know how to implement server-side BouncyCastle TLS PSK?

    ReplyReplies
    • Himanshu Rawal5/28/2015 8:00 AM

      Hey, do you get any way to use tls_psk on both sides client and server in java. I do not know how to start . Plz help me at himanshu.rawal19@gmail.com or reply to this comment

    Reply

  2. Yuliang Hou11/12/2014 11:44 PM

    hi, brother. Do you have psk_tls code, both client and server. can you sent to me? now i need to use java implement tls psk, but I do not know how to start. please help me, thanks a lot

    Reply
  3. Anonymous1/02/2015 1:30 PM

    @Override
    public int[] getCipherSuites()
    {
    return new int[] { CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256, CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA};
    }

    Reply
  4. Himanshu Rawal5/28/2015 8:02 AM

    Hey, do you get any way to use tls_psk on both sides client and server in java. I do not know how to start . Plz help me at himanshu.rawal19@gmail.com or reply to this comment

    Reply
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
安装 Bouncy Castle 是相对简单的过程,您只需要遵循以下步骤即可: 1. 访问 Bouncy Castle 官方网站:https://www.bouncycastle.org/ 2. 点击下载页面中的 “Downloads” 链接,然后选择您需要的版本,例如 “Bouncy Castle Provider 1.68” 。 3. 下载适合您操作系统的版本。 4. 解压下载的压缩包,您会发现其中包含了一个 JAR 文件。 5. 将该 JAR 文件添加到您的 Java 项目中,以便您可以使用 Bouncy Castle 提供的安全功能。具体方法取决于您使用的构建工具,但通常包括以下步骤: a. 在您的项目中创建一个名为 “lib” 的目录(如果您没有这样做)。 b. 将下载的 JAR 文件复制到这个目录中。 c. 在您的项目设置中添加对该 JAR 文件的引用。 6. 完成以上步骤后,您就可以使用 Bouncy Castle 提供的安全功能了。例如,在 Java 中使用 Bouncy Castle 加密数据的示例代码如下: ``` import org.bouncycastle.jce.provider.BouncyCastleProvider; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.Security; public class BouncyCastleExample { public static void main(String[] args) throws Exception { Security.addProvider(new BouncyCastleProvider()); byte[] key = "0123456789abcdef".getBytes(); byte[] iv = "fedcba9876543210".getBytes(); byte[] plaintext = "Hello, world!".getBytes(); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC"); SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); byte[] ciphertext = cipher.doFinal(plaintext); System.out.println(new String(ciphertext)); } } ``` 希望这可以帮助您安装和使用 Bouncy Castle 库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值