java之Asymmetric encryption techniques

来源:互联网 发布:bioeffect蓓欧菲 知乎 编辑:程序博客网 时间:2024/05/22 17:37

java之Asymmetric encryption techniques


Asymmetric encryption uses a public and private key. The private key is held by one entity. The public key is made available to everyone. Data can be encrypted using either key:
If the data is encrypted using the private key, then it can be decrypted using the public key.
If the data is encrypted using the public key, then it can be decrypted using the private key.

If the owner of the private key sends out a message that is encrypted with the private key, then recipients of this message can decrypt it with the public key. They can all read the message, but they know that only the private key owner could have sent this message. If someone else encrypts a message with the public key, then only the private key owner can read that message. However, the owner cannot be sure who actually sent the message. It could be an impostor.
However, if both the parties have their own set of public/private keys, we can guarantee that only the sender and the recipient can see its content. We can also guarantee that the sender is who they say they are.
Let’s assume that Sue wants to send a message to Bob. Sue will encrypt the message, M, using her private key. Let’s call this message M1. She will then encrypt M1 using Bob’s public key giving us M2. The message, M2, is then sent to Bob. Now, only Bob can decrypt this message using his private key. This will return M1. Bob can now use Sue’s public key to decrypt M1 to get the original message, M. He knows that this is from Sue because only Sue’s public key will work.
This process to send messages requires that both participants possess their own public/private keys. In addition to this, it is not as efficient as using a symmetric key. Another approach is to use asymmetric keys to transfer a secret key to the participants. The secret key can then be used for the actual message transfer. This is the technique that
is used with SSL.
There are several asymmetric algorithms. Java supports the following encryption algorithms:
RSA
Diffie-Hellman
DSA


package com.doctor.ch08;import java.nio.charset.StandardCharsets;import java.security.InvalidKeyException;import java.security.KeyFactory;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.NoSuchAlgorithmException;import java.security.PrivateKey;import java.security.PublicKey;import java.security.spec.InvalidKeySpecException;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.Base64;import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.NoSuchPaddingException;import org.apache.commons.lang3.tuple.ImmutablePair;import org.apache.commons.lang3.tuple.Pair;/** * Asymmetric encryption techniques *  * @author sdcuike * *         Created on 2016年4月16日 下午2:50:41 */public class AsymmetricEncryptionTechniques {    static final String rsa_algorithm = "RSA";    public static void main(String[] args) throws Throwable {        String message = "hello doctor?";        Pair<String, String> base64PrivateAndPublicKey = generateBase64PrivateAndPublicKey();        System.out.println("Private key:" + base64PrivateAndPublicKey.getLeft());        System.out.println("Public key:" + base64PrivateAndPublicKey.getRight());        System.out.println("==========================");        String encryptedBase64String = encryptToBase64String(base64PrivateAndPublicKey, message);        System.out.println(encryptedBase64String);        String decrypt = decrypt(base64PrivateAndPublicKey, encryptedBase64String);        System.out.println(decrypt);    }    static String encryptToBase64String(Pair<String, String> base64PrivateAndPublicKey, String message) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException {        Cipher cipher = Cipher.getInstance(rsa_algorithm);        PublicKey publicKey = getPublicKey(base64PrivateAndPublicKey);        cipher.init(Cipher.ENCRYPT_MODE, publicKey);        byte[] doFinal = cipher.doFinal(message.getBytes(StandardCharsets.UTF_8));        return Base64.getEncoder().encodeToString(doFinal);    }    static String decrypt(Pair<String, String> base64PrivateAndPublicKey, String encryptedBase64String) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {        byte[] decode = Base64.getDecoder().decode(encryptedBase64String);        Cipher cipher = Cipher.getInstance(rsa_algorithm);        PrivateKey privateKey = getPrivateKey(base64PrivateAndPublicKey);        cipher.init(Cipher.DECRYPT_MODE, privateKey);        byte[] doFinal = cipher.doFinal(decode);        return new String(doFinal, StandardCharsets.UTF_8);    }    static Pair<String, String> generateBase64PrivateAndPublicKey() throws NoSuchAlgorithmException {        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(rsa_algorithm);        keyPairGenerator.initialize(1024);        KeyPair keyPair = keyPairGenerator.generateKeyPair();        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyPair.getPrivate().getEncoded());        String privateKey = Base64.getEncoder().encodeToString(pkcs8EncodedKeySpec.getEncoded());        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyPair.getPublic().getEncoded());        String publicKey = Base64.getEncoder().encodeToString(x509EncodedKeySpec.getEncoded());        return new ImmutablePair<String, String>(privateKey, publicKey);    }    static PrivateKey getPrivateKey(Pair<String, String> base64PrivateAndPublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {        String base64PrivateKey = base64PrivateAndPublicKey.getLeft();        byte[] decode = Base64.getDecoder().decode(base64PrivateKey);        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decode);        KeyFactory keyFactory = KeyFactory.getInstance(rsa_algorithm);        return keyFactory.generatePrivate(pkcs8EncodedKeySpec);    }    static PublicKey getPublicKey(Pair<String, String> base64PrivateAndPublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {        String base64PublicKey = base64PrivateAndPublicKey.getRight();        byte[] decode = Base64.getDecoder().decode(base64PublicKey);        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(decode);        KeyFactory keyFactory = KeyFactory.getInstance(rsa_algorithm);        return keyFactory.generatePublic(x509EncodedKeySpec);    }}


Private key:MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAILhgOPehf0TVpNt54udCB9gxD4r+GH2cHfkNG3wm/dKdfL/ki/Jz+c/gnFb+D9sxHJHjfdwukKVjvkjDhj16k8XqNw1TrtarO1G5+/BqWFBIoc+9tc/dE5AGLPKeH0OVuHujhVWy13zAAVElszt1bRsK3fRnYgnUoL+Dy7AuZZ7AgMBAAECgYBv8uUlg/wF2ZmvJ03rzJjbBhE1wLSHTp0q38a81xcBMe6ruFFZkPzFJzyzK+Cul6F8wpm7MfAP7g9KKOLxFL+iQqvQqu3rpQUPX3xIcoABJnoaP0kQaDKZtkuEZZitD50nUfL/P/CL+8PfmI0NDlUuiVKeHEswZmkbfi65o0yYWQJBAN02YBHVLUBFoK+BdMnJc+Fg79AtgnC7rja2KxAs53L6XKmk6ihUBhLjVlhG2P5poxaK9rlUzNqhNp3cbB+mbZUCQQCXdonmQk7hgwy6IK/BtMEm1tsQpA8B9LOYvoUDsAlv94Wf+ue3fSE1q9v9nz0Q32qB+D5swlB+WXPDT2Pmfk/PAkEA2qTL/9Q8jbJESDQkQu4i4zj0z0asDtDyOJGFrs8zVKmwvNyLtKCYAENDLK2Z/Jxc3gMsKbJvaAi/+vfKxt2woQJACrgK3k7HAlKh7fIuPgkqujLuYekaXssQgrjI9Q/aOyBLRp0dFPE4DnJRKUvBqJYHFZeZ41yFEcwG00WlDkTWJQJAWtIAFhPOYpW6WWpB9SeyXqMDZkvEb9Hjl6svCTc6LSH/lnq94AzoizvIMgjJZIBuvo8lgDP27SnbEj6QYj8A2Q==Public key:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCC4YDj3oX9E1aTbeeLnQgfYMQ+K/hh9nB35DRt8Jv3SnXy/5Ivyc/nP4JxW/g/bMRyR433cLpClY75Iw4Y9epPF6jcNU67WqztRufvwalhQSKHPvbXP3ROQBizynh9Dlbh7o4VVstd8wAFRJbM7dW0bCt30Z2IJ1KC/g8uwLmWewIDAQAB==========================V+AxVzkKoUY5QfCWIoRVXTZiVXOj6izweJzEGuYKpVA9UjXxrw4FUuPg8r5h9Sf4s/179vmkVLM1sesLsMSTSjF5PCJYszJETOdEorjTtqpLpgUYJ6pWMwXvNEmyLnMhRucAMC5naVhuxnUa+J8UM0Fm9WlDMYSP5/lDsLDOa0Y=hello doctor?



读书笔记:
Learning Network Programming with Java
Copyright © 2015 Packt Publishing

First published: December 2015
Production reference: 1141215
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-547-1
www.packtpub.com


1 0
原创粉丝点击