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;

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值