JAVA安全-非对称加密(二)

非对称加密会产生两个东西,一个是公钥,一个是私钥,公开密钥与私有密钥是一对,如果用公开密钥对数据进行加密,只有用对应的私有密钥才能解密;如果用私有密钥对数据进行加密,那么只有用对应的公开密钥才能解密。

非对称加密特点

  • 公开密钥是对大众公开的,私密密钥是服务器私有的,两者不能互推得出。
  • 用公开密钥对数据进行加密,私密密钥可解密;私密密钥对数据加密,公开密钥可解密。
  • 速度较对称加密慢。

常见加密算法--RSA

加密:

一般来说,我们通过公开密钥对信息加密,然后发送给服务端,服务端再用私密密钥解密,获取保密的信息。(而RSA中通过私密密钥加密,然后通过公开密钥正确地解密获取信息,但这个过程对于加密来说没有意义,因为公开密钥是公开的,也就是说大家都可以解密。所以私密密钥加密、公开密钥解密用于签名功能)

签名:

签名的目的在于证明给大伙看这份信息是本人所发,并且发送过程中没被篡改。服务端对于将要发送的信息进行摘要操作(比如MD5),然后对其摘要值用私密密钥加密,形成签名值,将发送的信息与签名值发送出去。客户端收到信息和签名值后,用公开密钥将签名值解密,然后将信息进行摘要操作,再比对两者的摘要值,就可知该信息是否服务端所发,发送过程是否有篡改。

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

public class RSAUtil {
    public static final String ENCRYPTION_ALGORITHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**
     * 生成密钥
     */
    public static Map initKey() throws Exception {
        /* 初始化密钥生成器 */
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ENCRYPTION_ALGORITHM);
        keyPairGenerator.initialize(1024);

        /* 生成密钥 */
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        Map keyMap = new HashMap(2);
        keyMap.put("PublicKey", publicKey);
        keyMap.put("PrivateKey", privateKey);
        return keyMap;
    }
    
    /**
     * 取得公钥
     */
    public static String getPublicKey(Map keyMap)
            throws Exception {
        Key key = (Key) keyMap.get("PublicKey");
        return Base64Util.encryptBASE64(key.getEncoded());
    }
    
    /**
     * 取得私钥
     */
    public static String getPrivateKey(Map keyMap)
            throws Exception {
        Key key = (Key) keyMap.get("PrivateKey");
        return Base64Util.encryptBASE64(key.getEncoded());
    }
    
    /**
     * 加密
     */
    public static byte[] encrypt(byte[] data, String keyString, boolean isPublic) throws Exception {
        Map keyAndFactoryMap = RSAUtil.generateKeyAndFactory(keyString, isPublic);
        KeyFactory keyFactory = RSAUtil.getKeyFactory(keyAndFactoryMap);
        Key key = RSAUtil.getKey(keyAndFactoryMap);
        
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, key);

        return cipher.doFinal(data);
    }
    
    /**
     * 解密
     */
    public static byte[] decrypt(byte[] data, String keyString, boolean isPublic) throws Exception {
        Map keyAndFactoryMap = RSAUtil.generateKeyAndFactory(keyString, isPublic);
        KeyFactory keyFactory = RSAUtil.getKeyFactory(keyAndFactoryMap);
        Key key = RSAUtil.getKey(keyAndFactoryMap);
        
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, key);

        return cipher.doFinal(data);
    }
    
    /**
     * 生成钥匙
     */
    public static Map generateKeyAndFactory(String keyString, boolean isPublic) throws Exception {
        byte[] keyBytes = Base64Util.decryptBASE64(keyString);
        
        KeyFactory keyFactory = KeyFactory.getInstance(ENCRYPTION_ALGORITHM);
        Key key = null;
        if (isPublic) {
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            key = keyFactory.generatePublic(x509KeySpec);
        } else {
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            key = keyFactory.generatePrivate(pkcs8KeySpec);
        }
        
        Map keyAndFactoryMap = new HashMap(2);
        keyAndFactoryMap.put("key", key);
        keyAndFactoryMap.put("keyFactory", keyFactory);
        
        return keyAndFactoryMap;
    }
    
    /**
     * 从指定对象中获取钥匙
     */
    public static Key getKey(Map map) {
        if (map.get("key") == null) {
            return null;
        }
        return (Key)map.get("key");
    }

    /**
     * 从指定对象中获取钥匙工厂
     */
    public static KeyFactory getKeyFactory(Map map) {
        if (map.get("keyFactory") == null) {
            return null;
        }
        return (KeyFactory)map.get("keyFactory");
    }
    
    /**
     * 对信息生成数字签名(用私钥)
     */
    public static String sign(byte[] data, String keyString) throws Exception {
        Map keyAndFactoryMap = RSAUtil.generateKeyAndFactory(keyString, false);
        Key key = RSAUtil.getKey(keyAndFactoryMap);
        
        PrivateKey privateKey = (PrivateKey)key;

        // 用私钥对信息生成数字签名
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateKey);
        signature.update(data);

        return Base64Util.encryptBASE64(signature.sign());
    }

    /**
     * 校验数字签名(用公钥)
     */
    public static boolean verify(byte[] data, String keyString, String sign)
            throws Exception {
        Map keyAndFactoryMap = RSAUtil.generateKeyAndFactory(keyString, true);
        Key key = RSAUtil.getKey(keyAndFactoryMap);
        
        PublicKey publicKey = (PublicKey)key;

        // 取公钥匙对象
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicKey);
        signature.update(data);

        // 验证签名是否正常
        return signature.verify(Base64Util.decryptBASE64(sign));
    }

}

 

你可能感兴趣的:(安全,加密,JAVA--基础知识整理)