RSA加密解密操作

国内私募机构九鼎控股打造APP,来就送 20元现金领取地址: http://jdb.jiudingcapital.com/phone.html
内部邀请码: C8E245J (不写邀请码,没有现金送)
国内私募机构九鼎控股打造,九鼎投资是在全国股份转让系统挂牌的公众公司,股票代码为430719,为“中国PE第一股”,市值超1000亿元。 

 

------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

 

原文地址: http://wlh.iteye.com/blog/134796

生成RSA密钥、保存到文件、从文件读取、加密、解密等操作。

import java.security.Key;   
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.SecureRandom;   
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 javax.crypto.Cipher;   
import org.apache.commons.configuration.ConfigurationException;   
import org.apache.commons.configuration.PropertiesConfiguration;   
import org.bouncycastle.jce.provider.BouncyCastleProvider;   
  
public class RSATest {   
  
    public static void main(String[] args) {   
        try {   
            RSATest encrypt = new RSATest();   
            String encryptText = "encryptText";   
  
            // Generate keys   
            KeyPair keyPair = encrypt.generateKey();   
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();   
  
            byte[] e = encrypt.encrypt(publicKey, encryptText.getBytes());   
            byte[] de = encrypt.decrypt(privateKey, e);   
            System.out.println(toHexString(e));   
            System.out.println(toHexString(de));   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
  
    public KeyPair generateKey() throws NoSuchAlgorithmException {   
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");   
        keyPairGen.initialize(1024, new SecureRandom());   
  
        KeyPair keyPair = keyPairGen.generateKeyPair();   
        return keyPair;   
    }   
  
    public void saveKey(KeyPair keyPair, String publicKeyFile,   
            String privateKeyFile) throws ConfigurationException {   
        PublicKey pubkey = keyPair.getPublic();   
        PrivateKey prikey = keyPair.getPrivate();   
  
        // save public key   
        PropertiesConfiguration publicConfig = new PropertiesConfiguration(   
                publicKeyFile);   
        publicConfig.setProperty("PULIICKEY", toHexString(pubkey.getEncoded()));   
        publicConfig.save();   
  
        // save private key   
        PropertiesConfiguration privateConfig = new PropertiesConfiguration(   
                privateKeyFile);   
        privateConfig.setProperty("PRIVATEKEY",   
                toHexString(prikey.getEncoded()));   
        privateConfig.save();   
    }   
  
    /**  
     * @param filename  
     * @param type:  
     *            1-public 0-private  
     * @return  
     * @throws ConfigurationException  
     * @throws NoSuchAlgorithmException  
     * @throws InvalidKeySpecException  
     */  
    public Key loadKey(String filename, int type)   
            throws ConfigurationException, NoSuchAlgorithmException,   
            InvalidKeySpecException {   
        PropertiesConfiguration config = new PropertiesConfiguration(filename);   
        KeyFactory keyFactory = KeyFactory.getInstance("RSA",   
                new BouncyCastleProvider());   
  
        if (type == 0) {   
            // privateKey   
            String privateKeyValue = config.getString("PULIICKEY");   
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(   
                    toBytes(privateKeyValue));   
            PrivateKey privateKey = keyFactory.generatePrivate(priPKCS8);   
            return privateKey;   
  
        } else {   
            // publicKey   
            String privateKeyValue = config.getString("PRIVATEKEY");   
            X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(   
                    toBytes(privateKeyValue));   
            PublicKey publicKey = keyFactory.generatePublic(bobPubKeySpec);   
            return publicKey;   
        }   
    }   
  
    /**  
     * Encrypt String.  
     *   
     * @return byte[]  
     */  
    protected byte[] encrypt(RSAPublicKey publicKey, byte[] data) {   
        if (publicKey != null) {   
            try {   
                Cipher cipher = Cipher.getInstance("RSA",   
                        new BouncyCastleProvider());   
                cipher.init(Cipher.ENCRYPT_MODE, publicKey);   
                return cipher.doFinal(data);   
            } catch (Exception e) {   
                e.printStackTrace();   
            }   
        }   
        return null;   
    }   
  
    /**  
     * Basic decrypt method  
     *   
     * @return byte[]  
     */  
    protected byte[] decrypt(RSAPrivateKey privateKey, byte[] raw) {   
        if (privateKey != null) {   
            try {   
                Cipher cipher = Cipher.getInstance("RSA",   
                        new BouncyCastleProvider());   
                cipher.init(Cipher.DECRYPT_MODE, privateKey);   
                return cipher.doFinal(raw);   
            } catch (Exception e) {   
                e.printStackTrace();   
            }   
        }   
  
        return null;   
    }   
  
    public static String toHexString(byte[] b) {   
        StringBuilder sb = new StringBuilder(b.length * 2);   
        for (int i = 0; i < b.length; i++) {   
            sb.append(HEXCHAR[(b[i] & 0xf0) >>> 4]);   
            sb.append(HEXCHAR[b[i] & 0x0f]);   
        }   
        return sb.toString();   
    }   
  
    public static final byte[] toBytes(String s) {   
        byte[] bytes;   
        bytes = new byte[s.length() / 2];   
        for (int i = 0; i < bytes.length; i++) {   
            bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2),   
                    16);   
        }   
        return bytes;   
    }   
  
    private static char[] HEXCHAR = { '0', '1', '2', '3', '4', '5', '6', '7',   
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };   
  
}   

 

转载于:https://www.cnblogs.com/AloneSword/p/3327368.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值