集册 Java实例教程 在SecureClient/Server中完成密钥交换,不在本地进行套接字通信

在SecureClient/Server中完成密钥交换,不在本地进行套接字通信

欢马劈雪     最近更新时间:2020-01-02 10:19:05

536
在SecureClient/Server中完成密钥交换,不进行本地套接字通信


import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

/*
NowJava.com 提供
*/

import javax.crypto.*;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;

import java.io.UnsupportedEncodingException;

import java.security.*;


public class Test {


    private static final Logger logger = LogManager.getLogger(Test.class);


    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
    /* 
     来自 
    *N o w  J a v a  .   c o m*/


        String message = "Just Read the Instructions";


        // generate Public and Private Key

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

        SecureRandom random = SecureRandom.getInstanceStrong();


        keyPairGenerator.initialize(2048, random);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        PublicKey publicKey = keyPair.getPublic();

        PrivateKey privateKey = keyPair.getPrivate();


        // generates synchronous public key

        KeyGenerator keyGen = KeyGenerator.getInstance("AES");

        keyGen.init(128);

        SecretKey secretKey = keyGen.generateKey();


        // uses public key from client to encrypt synchronous public key

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        byte[] encryptedData = cipher.doFinal(secretKey.getEncoded());


        // DECRYPTION of AES Key

        cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        SecretKey aesKey = new SecretKeySpec(cipher.doFinal(encryptedData), "AES");


        // use the AES key for encrypting a message

        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        byte[] iv = new byte[16];

        random = new SecureRandom();

        random.nextBytes(iv);

        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        cipher.init(Cipher.ENCRYPT_MODE, aesKey, ivParameterSpec);

        encryptedData = cipher.doFinal(message.getBytes("UTF-8"));

        String encryp
展开阅读全文