Java 加密整理

Wesley13
• 阅读 337

对加密使用的整理:

1.需要导入jar包

'org.bouncycastle:bcprov-jdk16:1.46',
'commons-codec:commons-codec:1.9',

2.没有找到对应的加密算法名称,定义了算法名称Enum:EncryptAlgorithmEnum.java

/**
 * 
 */
package org.rico.commons.utils.encrypt;

/**
 * @author rico
 * 加密算法名称enum
 */
public enum EncryptAlgorithmEnum {
    MD5("MD5"),
    SHA("SHA"),
    SHA1("SHA1"),
    SHA256("SHA256"),
    
    DSA("DSA"),
    RSA("RSA"),
    
    AES("AES"),
    DES("DES"),
    DESede("DESede");
    
    
    private String name;
    
    private EncryptAlgorithmEnum(String name) {
        this.name = name;
    }
    
    public String value() {
        return this.getName();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

3.加密工具类EncryptUtil.java

/**
 * 
 */
package org.rc.common.encrypt;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * @author rico
 * md5加密工具 
 * message-digest algorithm 5 (信息-摘要算法),常用于文件校验
 * 
 * SHA(Secure Hash Algorithm,安全散列算法)
 * 数字签名等密码学应用中重要的工具,被广泛地应用于电子商务等信息安全领域。
 * SHA与MD5通过碰撞法都被破解了,但是SHA仍然是公认的安全加密算法,较之MD5更为安全
 * https://my.oschina.net/u/733161/blog/756814
 */
public class EncryptUtil {
    private static final String CHARSET_UTF8 = "UTF-8";
    
    static {
        //TODO add Provider
        // Adds a provider to the next position available. 
        Security.addProvider(new BouncyCastleProvider());
    }
    
    
    //============================================================================
    // 单向加密 MD5,SHA
    //============================================================================
    /**
     * 单向加密
     * @param value
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static byte[] digest(String algorithm, String value) throws NoSuchAlgorithmException {
        if(StringUtils.isBlank(algorithm)) {
            throw new NullPointerException("algorithm is null.");
        }
        if(StringUtils.isBlank(value)) {
            throw new NullPointerException("digest value is null.");
        }
        
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        digest.update(value.getBytes());
        
        return digest.digest();
    }
    
    /**
     * 单向加密并转换为字符串格式
     * @param value
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String digestToString(String algorithm, String value) throws NoSuchAlgorithmException {
        byte[] bytes = digest(algorithm, value);
        return Base64.encodeBase64String(bytes);
    }
    
    /**
     * md5 加密
     * @param value
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static byte[] md5(String value) throws NoSuchAlgorithmException {
        return digest(EncryptAlgorithmEnum.MD5.value(), value);
    }
    
    /**
     * md5加密并转换为字符串格式
     * @param value
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String md5ToString(String value) throws NoSuchAlgorithmException {
        return digestToString(EncryptAlgorithmEnum.MD5.value(), value);
    }
    
    /**
     * sha加密
     * @param value
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static byte[] sha(String value) throws NoSuchAlgorithmException {
        return digest(EncryptAlgorithmEnum.SHA.value(), value);
    }
    
    /**
     * sha加密并转换为字符串格式
     * @param value
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String shaToString(String value) throws NoSuchAlgorithmException {
        return digestToString(EncryptAlgorithmEnum.SHA.value(), value);
    }
    
    
    //===============================================================================
    // 对称双向加密AES,DES
    //===============================================================================
    /**
     * 生成密钥
     * @param algorithm
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static SecretKey generateSecretKey(String algorithm) throws NoSuchAlgorithmException {
        if(StringUtils.isBlank(algorithm)) {
            throw new NullPointerException("algorithm name is null");
        }
        KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
        return keyGenerator.generateKey();
    }
    
    /**
     * 生成密钥字符串
     * @param algorithm
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String generateSecretKeyString(String algorithm) throws NoSuchAlgorithmException {
        SecretKey secretKey = generateSecretKey(algorithm);
        return Base64.encodeBase64String(secretKey.getEncoded());
    }

    /**
     * 生成AES密钥
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static SecretKey aesKey() throws NoSuchAlgorithmException {
        return generateSecretKey(EncryptAlgorithmEnum.AES.value());
    }
    
    /**
     * 生成AES密钥字符串
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String aesKeyString() throws NoSuchAlgorithmException {
        return generateSecretKeyString(EncryptAlgorithmEnum.AES.value());
    }
    
    /**
     * 生成DES密钥
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static SecretKey desKey() throws NoSuchAlgorithmException {
        return generateSecretKey(EncryptAlgorithmEnum.DES.value());
    }
    
    /**
     * 生成DES密钥字符串
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String desKeyString() throws NoSuchAlgorithmException {
        return generateSecretKeyString(EncryptAlgorithmEnum.DES.value());
    }
    
    /**
     * 解析SecretKey
     * @param algorithm
     * @param value
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static SecretKey parseSecretKey(String algorithm, String value) throws NoSuchAlgorithmException {
        byte[] bytes = Base64.decodeBase64(value);
        return parseSecretKey(algorithm, bytes);
    }
    
    /**
     * 解析SecretKey
     * @param algorithm
     * @param bytes
     * @return
     */
    public static SecretKey parseSecretKey(String algorithm, byte[] bytes) {
        SecretKey secretKey = new SecretKeySpec(bytes, 0, bytes.length, algorithm);
        return secretKey;
    }
    
    /**
     * 解析 AES SecretKey
     * @param value
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static SecretKey parseAESSecretKey(String value) throws NoSuchAlgorithmException {
        return parseSecretKey(EncryptAlgorithmEnum.AES.value(), value);
    }
    public static SecretKey parseAESSecretKey(byte[] byets) throws NoSuchAlgorithmException {
        return parseSecretKey(EncryptAlgorithmEnum.AES.value(), byets);
    }
    
    /**
     * 解析 DES SecretKey
     * @param value
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static SecretKey parseDESSecretKey(String value) throws NoSuchAlgorithmException {
        return parseSecretKey(EncryptAlgorithmEnum.DES.value(), value);
    }
    public static SecretKey parseDESSecretKey(byte[] bytes) throws NoSuchAlgorithmException {
        return parseSecretKey(EncryptAlgorithmEnum.DES.value(), bytes);
    }
    
    /**
     * 对称加密
     * @param algorithm
     * @param key
     * @param value
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public static byte[] encryptSymmetric(String algorithm, SecretKey key, String value) throws NoSuchAlgorithmException, 
            NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        if(StringUtils.isBlank(algorithm)) {
            throw new NullPointerException("algorithm name is null");
        }
        if(StringUtils.isBlank(value)) {
            throw new NullPointerException("encrypt value is null");
        }
        
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(value.getBytes());
    }
    public static String encryptSymmetricString(String algorithm, SecretKey key, String value) throws NoSuchAlgorithmException, 
            NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        byte[] bytes = encryptSymmetric(algorithm, key, value);
        return Base64.encodeBase64String(bytes);
    }
    
    /**
     * 对称解密
     * @param algorithm
     * @param key
     * @param value
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     */
    public static byte[] decryptSymmetric(String algorithm, SecretKey key, String value) throws NoSuchAlgorithmException, 
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        
        if(StringUtils.isBlank(algorithm)) {
            throw new NullPointerException("algorithm name is null");
        }
        if(StringUtils.isBlank(value)) {
            throw new NullPointerException("decrypt value is null");
        }
        
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key);
        
        byte[] decodeBytes = Base64.decodeBase64(value);
        return cipher.doFinal(decodeBytes);
    }
    public static String decryptSymmetricString(String algorithm, SecretKey key, String value) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        byte[] bytes = decryptSymmetric(algorithm, key, value);
        return new String(bytes, CHARSET_UTF8);
    }
    
    /**
     * DES对称加密
     * @param key
     * @param value
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public static byte[] desEncrypt(SecretKey key, String value) throws InvalidKeyException, NoSuchAlgorithmException, 
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        return encryptSymmetric(EncryptAlgorithmEnum.DES.value(), key, value);
    }
    public static String desEncryptString(SecretKey key, String value) throws InvalidKeyException, NoSuchAlgorithmException, 
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        return encryptSymmetricString(EncryptAlgorithmEnum.DES.value(), key, value);
    }
    
    /**
     * DES对称解密
     * @param key
     * @param value
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     */
    public static String desDecryptString(SecretKey key, String value) throws InvalidKeyException, NoSuchAlgorithmException, 
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        return decryptSymmetricString(EncryptAlgorithmEnum.DES.value(), key, value);
    }
    public static byte[] desDecrypt(SecretKey key, String value) throws InvalidKeyException, NoSuchAlgorithmException, 
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        return decryptSymmetric(EncryptAlgorithmEnum.DES.value(), key, value);
    }
    
    /**
     * AES对称加密
     * @param key
     * @param value
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public static byte[] aesEncrypt(SecretKey key, String value) throws InvalidKeyException, NoSuchAlgorithmException, 
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        return encryptSymmetric(EncryptAlgorithmEnum.AES.value(), key, value);
    }
    public static String aesEncryptString(SecretKey key, String value) throws InvalidKeyException, NoSuchAlgorithmException, 
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        return encryptSymmetricString(EncryptAlgorithmEnum.AES.value(), key, value);
    }
    
    /**
     * AES对称解密
     * @param key
     * @param value
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     */
    public static byte[] aesDecrypt(SecretKey key, String value) throws InvalidKeyException, NoSuchAlgorithmException, 
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        return decryptSymmetric(EncryptAlgorithmEnum.AES.value(), key, value);
    }
    public static String aesDecryptString(SecretKey key, String value) throws InvalidKeyException, NoSuchAlgorithmException, 
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        return decryptSymmetricString(EncryptAlgorithmEnum.AES.value(), key, value);
    }
    
    
    //=================================================================================
    // 非对称双向加密RSA/DSA
    //===========================非对称双向加密=========================================
    /**
     * 生成密钥对
     * @param algorithm
     * @param keysize
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static KeyPair generateKeyPair(String algorithm, int keysize) throws NoSuchAlgorithmException {
        if(StringUtils.isBlank(algorithm)) {
            throw new NullPointerException("algorithm name is null");
        }
        if(keysize <= 0) {
            throw new IllegalArgumentException("keysize should be great than zero.");
        }
        
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        keyPairGenerator.initialize(keysize);
        
        return keyPairGenerator.generateKeyPair();
    }
    
    /**
     * 生成密钥对
     * @param algorithm
     * @param keysize
     * @param random
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static KeyPair generateKeyPair(String algorithm, int keysize, SecureRandom random) throws NoSuchAlgorithmException {
        if(StringUtils.isBlank(algorithm)) {
            throw new NullPointerException("algorithm name is null");
        }
        if(keysize <= 0) {
            throw new IllegalArgumentException("keysize should be great than zero.");
        }
        
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        keyPairGenerator.initialize(keysize, random);
        
        return keyPairGenerator.generateKeyPair();
    }
    
    /**
     * 获取RSA密钥对
     * @param keysize
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static KeyPair rsaKeyPair(int keysize) throws NoSuchAlgorithmException {
        return generateKeyPair(EncryptAlgorithmEnum.RSA.value(), keysize);
    }
    public static KeyPair rsaKeyPair(int keysize, SecureRandom random) throws NoSuchAlgorithmException {
        return generateKeyPair(EncryptAlgorithmEnum.RSA.value(), keysize, random);
    }
    
    /**
     * 获取DSA密钥对
     * @param keysize
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static KeyPair dsaKeyPair(int keysize) throws NoSuchAlgorithmException {
        return generateKeyPair(EncryptAlgorithmEnum.DSA.value(), keysize);
    }
    public static KeyPair dsaKeyPair(int keysize, SecureRandom random) throws NoSuchAlgorithmException {
        return generateKeyPair(EncryptAlgorithmEnum.DSA.value(), keysize, random);
    }
    
    public static String keyToString(Key key) {
        return Base64.encodeBase64String(key.getEncoded());
    }
    
    /**
     * 非对称加密
     * @param algorithm
     * @param key
     * @param value
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     */
    public static byte[] encryptNonSymmetric(String algorithm, Key key, String value) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        if(StringUtils.isBlank(algorithm)) {
            throw new NullPointerException("algorithm name is null");
        }
        if(StringUtils.isBlank(value)) {
            throw new NullPointerException("encrypt value is null");
        }
        
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(value.getBytes(CHARSET_UTF8));
    }
    public static String encryptNonSymmetricString(String algorithm, Key key, String value) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        byte[] bytes = encryptNonSymmetric(algorithm, key, value);
        return Base64.encodeBase64String(bytes);
    }
    
    /**
     * 非对称解密
     * @param algorithm
     * @param key
     * @param value
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     */
    public static byte[] decryptNonSymmetric(String algorithm, Key key, String value) throws NoSuchAlgorithmException, NoSuchPaddingException, 
            InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        if(StringUtils.isBlank(algorithm)) {
            throw new NullPointerException("algorithm name is null");
        }
        if(StringUtils.isBlank(value)) {
            throw new NullPointerException("decrypt value is null");
        }
        
        byte[] bytes = Base64.decodeBase64(value);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(bytes);
    }
    public static String decryptNonSymmetricString(String algorithm, Key key, String value) throws NoSuchAlgorithmException, 
            NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        byte[] decryptBytes = decryptNonSymmetric(algorithm, key, value);
        return new String(decryptBytes, CHARSET_UTF8);
    }
    
    /**
     * RSA加密
     * @param key
     * @param value
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     */
    public static byte[] rsaEncrypt(Key key, String value) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, 
            IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        return encryptNonSymmetric(EncryptAlgorithmEnum.RSA.value(), key, value);
    }
    public static String rsaEncryptString(Key key, String value) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, 
            IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        return encryptNonSymmetricString(EncryptAlgorithmEnum.RSA.value(), key, value);
    }
    
    /**
     * RSA解密
     * @param key
     * @param value
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     */
    public static byte[] rsaDecrypt(Key key, String value) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, 
            IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        return decryptNonSymmetric(EncryptAlgorithmEnum.RSA.value(), key, value);
    }
    public static String rsaDecryptString(Key key, String value) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, 
            IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        return decryptNonSymmetricString(EncryptAlgorithmEnum.RSA.value(), key, value);
    }
    
    /**
     * DSA加密
     * @param key
     * @param value
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     */
    public static byte[] dsaEncrypt(Key key, String value) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, 
            IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        return encryptNonSymmetric(EncryptAlgorithmEnum.DSA.value(), key, value);
    }
    public static String dsaEncryptString(Key key, String value) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, 
            IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        return encryptNonSymmetricString(EncryptAlgorithmEnum.DSA.value(), key, value);
    }
    
    /**
     * DSA解密
     * @param algorithm
     * @param key
     * @param value
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     */
    public static byte[] dsaDecrypt(String algorithm, Key key, String value) throws InvalidKeyException, NoSuchAlgorithmException, 
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        return decryptNonSymmetric(EncryptAlgorithmEnum.DSA.value(), key, value);
    }
    public static String dsaDecryptString(String algorithm, Key key, String value) throws InvalidKeyException, NoSuchAlgorithmException, 
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        return decryptNonSymmetricString(EncryptAlgorithmEnum.DSA.value(), key, value);
    }
    
    /**
     * 解析私钥
     * @param keyFactory
     * @param keyValue
     * @return
     * @throws InvalidKeySpecException
     */
    public static PrivateKey parsePrivateKey(KeyFactory keyFactory, byte[] bytes) throws InvalidKeySpecException {
        // Creates a new PKCS8EncodedKeySpec with the given encoded key.
        // PKCS8EncodedKeySpec represents the ASN.1 encoding of a private key, encoded according to the ASN.1 type PrivateKeyInfo. 
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
        PrivateKey key = (PrivateKey) keyFactory.generatePrivate(keySpec);
        
        return key;
    }
    public static PrivateKey parsePrivateKey(KeyFactory keyFactory, String keyValue) throws InvalidKeySpecException {
        return parsePrivateKey(keyFactory, Base64.decodeBase64(keyValue.getBytes()));
    }
    
    /**
     * 解析私钥(RSA)
     * @param keyValue
     * @return
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     */
    public static PrivateKey parseRSAPrivateKey(byte[] bytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
        KeyFactory keyFactory = getKeyFactory(EncryptAlgorithmEnum.RSA.value());
        return parsePrivateKey(keyFactory, bytes);
    }
    public static PrivateKey parseRSAPrivateKey(String keyValue) throws InvalidKeySpecException, NoSuchAlgorithmException {
        KeyFactory keyFactory = getKeyFactory(EncryptAlgorithmEnum.RSA.value());
        return parsePrivateKey(keyFactory, keyValue);
    }
    
    /**
     * 解析私钥(DSA)
     * @param keyValue
     * @return
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     */
    public static PrivateKey parseDSAPrivateKey(byte[] bytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
        KeyFactory keyFactory = getKeyFactory(EncryptAlgorithmEnum.DSA.value());
        return parsePrivateKey(keyFactory, bytes);
    }
    public static PrivateKey parseDSAPrivateKey(String keyValue) throws InvalidKeySpecException, NoSuchAlgorithmException {
        KeyFactory keyFactory = getKeyFactory(EncryptAlgorithmEnum.DSA.value());
        return parsePrivateKey(keyFactory, keyValue);
    }
    
    /**
     * 解析公钥
     * @param keyFactory
     * @param keyValue
     * @return
     * @throws InvalidKeySpecException
     */
    public static PublicKey parsePublicKey(KeyFactory keyFactory, byte[] bytes) throws InvalidKeySpecException {
        // Creates a new X509EncodedKeySpec with the given encoded key.
        // X509EncodedKeySpec represents the ASN.1 encoding of a public key, encoded according to the ASN.1 type SubjectPublicKeyInfo. 
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
        PublicKey key = keyFactory.generatePublic(keySpec);
        
        return key;
    }
    public static PublicKey parsePublicKey(KeyFactory keyFactory, String keyValue) throws InvalidKeySpecException {
        return parsePublicKey(keyFactory, Base64.decodeBase64(keyValue.getBytes()));
    }
    
    /**
     * 解析公钥(RSA)
     * @param keyValue
     * @return
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     */
    public static PublicKey parseRSAPublicKey(byte[] bytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
        KeyFactory keyFactory = getKeyFactory(EncryptAlgorithmEnum.RSA.value());
        return parsePublicKey(keyFactory, bytes);
    }
    public static PublicKey parseRSAPublicKey(String keyValue) throws InvalidKeySpecException, NoSuchAlgorithmException {
        KeyFactory keyFactory = getKeyFactory(EncryptAlgorithmEnum.RSA.value());
        return parsePublicKey(keyFactory, keyValue);
    }
    
    /**
     * 解析公钥(DSA)
     * @param keyValue
     * @return
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     */
    public static PublicKey parseDSAPublicKey(byte[] bytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
        KeyFactory keyFactory = getKeyFactory(EncryptAlgorithmEnum.DSA.value());
        return parsePublicKey(keyFactory, bytes);
    }
    public static PublicKey parseDSAPublicKey(String keyValue) throws InvalidKeySpecException, NoSuchAlgorithmException {
        KeyFactory keyFactory = getKeyFactory(EncryptAlgorithmEnum.DSA.value());
        return parsePublicKey(keyFactory, keyValue);
    }
    
    
    /**
     * 获取秘钥工厂类
     * @param algorithm
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static KeyFactory getKeyFactory(String algorithm) throws NoSuchAlgorithmException {        
        return KeyFactory.getInstance(algorithm);
    }
    
    /**
     * 获取秘钥工厂类(RSA)
     * @param algorithm
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static KeyFactory getRSAKeyFactory() throws NoSuchAlgorithmException {
        return getKeyFactory(EncryptAlgorithmEnum.RSA.value());
    }
    
    /**
     * 获取秘钥工厂类(DSA)
     * @param algorithm
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static KeyFactory getDSAKeyFactory() throws NoSuchAlgorithmException {
        return getKeyFactory(EncryptAlgorithmEnum.DSA.value());
    }
    
}

附:

http://blog.csdn.net/u013142781/article/details/50405648

http://blog.csdn.net/wildandfly/article/details/21521857

点赞
收藏
评论区
推荐文章
Wesley13 Wesley13
2年前
QQ音乐API分析之
QQ音乐API加密参数分析1、背景2、QQ音乐sign计算3、Java代码实现4、总结1、背景不知道什么时候开始,各家音乐APP都开始对API进行加密,最近一段时间对六大音乐平台的加密算法进行了研究,逆向了网页端、安卓端等等,已经掌握了各家的加密算法。平台加密算法非加密接口专
Easter79 Easter79
2年前
sqlcipher 移植
sqlcipher简介  SQLCipher是一个对sqlite数据库进行aes256加密的开源库,提供透明,安全的256位AES加密的SQLite数据库文件,项目本身不提供加密算法,调用openssl的aes加密算法  SQLCipher的社区版的源代码是一个BSD风格的开源许可下发布,但是官方提供的二进制库需要购买
浅谈加密算法 aes
一、目标搞了这么多期签名和加密解密,今天我们聊聊高大上的东西:加密算法。加密算法我们整体可以分为:不可逆加密算法和可逆加密算法。不可逆加密算法常见的不可逆加密算法有MD5,HMAC,SHA1、SHA224、SHA256、SHA384,和SHA512。他们的特点是,不能从加密后的结果解密出原文,主要用于校检数据的一致性,防止篡改数据,我们之前分析的大部分s
Wesley13 Wesley13
2年前
SSH加密原理、RSA非对称加密算法学习与理解
   首先声明一下,这里所说的SSH,并不是Java传统的三大框架,而是一种建立在应用层和传输层基础上的安全外壳协议,熟悉Linux的朋友经常使用到一个SSHSecureShellCilent的工具,本文也是基于此工具加密原理的学习,在SSH的加密原理中,使用到了RSA非对称加密算法,本文也一并做了学习和了解。  非对称加密算法
Wesley13 Wesley13
2年前
java sm3加密算法
javasm3加密算法实现CreationTime2018年7月13日09点28分Author:Marydon1.准备工作    所需jar包:  bcprovjdk15on1.59.jar  c
kenx kenx
2年前
Java MD5和SHA256等常用加密算法
前言我们在做java项目开发的时候,在前后端接口分离模式下,接口信息需要加密处理,做签名认证,还有在用户登录信息密码等也都需要数据加密。信息加密是现在几乎所有项目都需要用到的技术,身份认证、单点登陆、信息通讯、支付交易等场景中经常会需要用到加密算法,所谓加密算法,就是将原本的明文通过一系列算法操作变成密文。1.BASE严格地说,属于编码格式,而非加密算法
Wesley13 Wesley13
2年前
JAVA加密算法(1)
密码学综述密码学基本功能机密性、鉴别、报文完整性、不可否认性基本模型sender加密算法密文解密算法receiver密钥源密码学算法分类:消息编码:Base64消息摘要:MD类,SHA类,MAC对称加密:DES,3DES,AES
Wesley13 Wesley13
2年前
JAVA_RSA_的加解密
RSA为非对称加密算法。数字签名的过程:1、对明文数据进行HASH加密,不可逆;2、对加密后的数据再用RSA的私钥进行二次加密。数字签名的验证过程:1、对明文数据进行HASH加密,不可逆;2、用RSA的公钥对数字签名后的数据进行解密;3、把1的结果和2的结果进行比较是否相等。RSA加密的过程和解密的过程都需要三步:加/解密、分组、填充。这三部分每
Wesley13 Wesley13
2年前
JAVA加解密算法设计与应用
业务场景APP移动端、WEB、桌面端、第三方平台密码等敏感数据加密设计如app端登录密码加密设计对于登录密码不需要进行解密只需要加密算法结合规则进行比较就能得到密码正确与否方法一(签名保证安全)1.密码等敏感信息取Md5值对所有值(加上timestamp)
Wesley13 Wesley13
2年前
MD5 SHA1 HMAC HMAC_SHA1区别
MD5是一种不可逆的加密算法,目前是最牢靠的加密算法之一,尚没有能够逆运算的程序被开发出来,它对应任何字符串都可以加密成一段唯一的固定长度的代码。SHA1是由NISTNSA设计为同DSA一起使用的,它对长度小于264的输入,产生长度为160bit的散列值,因此抗穷举(bruteforce)性更好。HMAC\_SHA1