RSA非对称加密解密

RSA非对称加密解密



import org.apache.commons.codec.binary.Base64;

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.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
 * Created by zxf on 2016/9/22.
 */
public class Rsa {
    public static final String KEY_ALGORITHM = "RSA";
    /** 由于Android与服务器的的问题这里必须是:RSA/NONE/PKCS1Padding,未验证 */
    public static final String CIPHER_ALGORITHM = "RSA/NONE/PKCS1Padding";
    public static final String PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIRdil4gf0xCBbWWhLdXLcBNcDAxm131ZbrrA7p6kz3HKT3GqfoVQCwbgZ9JyvW/KhmNI4I2+PGX+Nbg1rLyDE0CAwEAAQ==";
    //public static final String PRIVATE_KEY = "privateKey";
    public static final String PRIVATE_KEY = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAhF2KXiB/TEIFtZaEt1ctwE1wMDGbXfVluusDunqTPccpPcap+hVALBuBn0nK9b8qGY0jgjb48Zf41uDWsvIMTQIDAQABAkBQXTKbP4PKWvN4crCVV/rRHLMWr6ey/kELoZCb8bvf71uEFLgk7Q9GEvM6F4ucH9Mp8qexJUBEWwGpmolkO4GJAiEA6nGVJ970KEjTYd4RuEJ0zrTilQZ0Q52Yk/kvtIiZFqMCIQCQiTQRQoJVBvL74tzbW++vFdPw4gadOs7BKTkjGYywTwIgTrBy/N/zmXXgJVAxKGR96keCabyx12QVK02POoxCvfsCIAhVkQYJwsAqZWp222tessRyysTSE7WPRYrH2L6YY49rAiEAxREH2PCWeA4Q4eh2JnpRFS3w2pdrvYUlT/97FG3oXlI=";

    /** RSA密钥长度必须是64的倍数,在512~65536之间。默认是1024 */
    public static final int KEY_SIZE = 1024;

    public static final String PLAIN_TEXT = "lamboo";

    public static void main(String[] args) {
        // 加密
        PublicKey publicKey = restorePublicKey(Base64.decodeBase64(PUBLIC_KEY));
        byte[] encodedText = RSAEncode(publicKey, PLAIN_TEXT.getBytes());
        System.out.println("RSA encoded: " + Base64.encodeBase64String(encodedText));

        // 解密

        PrivateKey privateKey = restorePrivateKey(Base64.decodeBase64(PRIVATE_KEY));
        System.out.println("RSA decoded: "+ RSADecode(privateKey, encodedText));
    }

    /**
     * 还原公钥,X509EncodedKeySpec 用于构建公钥的规范
     *
     * @param keyBytes
     * @return
     */
    public static PublicKey restorePublicKey(byte[] keyBytes) {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);

        try {
            KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
            return publicKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 还原私钥,PKCS8EncodedKeySpec 用于构建私钥的规范
     *
     * @param keyBytes
     * @return
     */
    public static PrivateKey restorePrivateKey(byte[] keyBytes) {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
                keyBytes);
        try {
            KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateKey = factory
                    .generatePrivate(pkcs8EncodedKeySpec);
            return privateKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 加密,三步走。
     *
     * @param key
     * @param plainText
     * @return
     */
    public static byte[] RSAEncode(PublicKey key, byte[] plainText) {

        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(plainText);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidKeyException | IllegalBlockSizeException
                | BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 解密,三步走。
     *
     * @param key
     * @param encodedText
     * @return
     */
    public static String RSADecode(PrivateKey key, byte[] encodedText) {

        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(encodedText));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidKeyException | IllegalBlockSizeException
                | BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }
}

猜你喜欢

转载自blog.csdn.net/lamboo_cn/article/details/52626462