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

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

java 代码
  1. import java.security.Key;   
  2. import java.security.KeyFactory;   
  3. import java.security.KeyPair;   
  4. import java.security.KeyPairGenerator;   
  5. import java.security.NoSuchAlgorithmException;   
  6. import java.security.PrivateKey;   
  7. import java.security.PublicKey;   
  8. import java.security.SecureRandom;   
  9. import java.security.interfaces.RSAPrivateKey;   
  10. import java.security.interfaces.RSAPublicKey;   
  11. import java.security.spec.InvalidKeySpecException;   
  12. import java.security.spec.PKCS8EncodedKeySpec;   
  13. import java.security.spec.X509EncodedKeySpec;   
  14. import javax.crypto.Cipher;   
  15. import org.apache.commons.configuration.ConfigurationException;   
  16. import org.apache.commons.configuration.PropertiesConfiguration;   
  17. import org.bouncycastle.jce.provider.BouncyCastleProvider;   
  18.   
  19. public class RSATest {   
  20.   
  21.     public static void main(String[] args) {   
  22.         try {   
  23.             RSATest encrypt = new RSATest();   
  24.             String encryptText = "encryptText";   
  25.   
  26.             // Generate keys   
  27.             KeyPair keyPair = encrypt.generateKey();   
  28.             RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   
  29.             RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();   
  30.   
  31.             byte[] e = encrypt.encrypt(publicKey, encryptText.getBytes());   
  32.             byte[] de = encrypt.decrypt(privateKey, e);   
  33.             System.out.println(toHexString(e));   
  34.             System.out.println(toHexString(de));   
  35.         } catch (Exception e) {   
  36.             e.printStackTrace();   
  37.         }   
  38.     }   
  39.   
  40.     public KeyPair generateKey() throws NoSuchAlgorithmException {   
  41.         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");   
  42.         keyPairGen.initialize(1024new SecureRandom());   
  43.   
  44.         KeyPair keyPair = keyPairGen.generateKeyPair();   
  45.         return keyPair;   
  46.     }   
  47.   
  48.     public void saveKey(KeyPair keyPair, String publicKeyFile,   
  49.             String privateKeyFile) throws ConfigurationException {   
  50.         PublicKey pubkey = keyPair.getPublic();   
  51.         PrivateKey prikey = keyPair.getPrivate();   
  52.   
  53.         // save public key   
  54.         PropertiesConfiguration publicConfig = new PropertiesConfiguration(   
  55.                 publicKeyFile);   
  56.         publicConfig.setProperty("PULIICKEY", toHexString(pubkey.getEncoded()));   
  57.         publicConfig.save();   
  58.   
  59.         // save private key   
  60.         PropertiesConfiguration privateConfig = new PropertiesConfiguration(   
  61.                 privateKeyFile);   
  62.         privateConfig.setProperty("PRIVATEKEY",   
  63.                 toHexString(prikey.getEncoded()));   
  64.         privateConfig.save();   
  65.     }   
  66.   
  67.     /**  
  68.      * @param filename  
  69.      * @param type:  
  70.      *            1-public 0-private  
  71.      * @return  
  72.      * @throws ConfigurationException  
  73.      * @throws NoSuchAlgorithmException  
  74.      * @throws InvalidKeySpecException  
  75.      */  
  76.     public Key loadKey(String filename, int type)   
  77.             throws ConfigurationException, NoSuchAlgorithmException,   
  78.             InvalidKeySpecException {   
  79.         PropertiesConfiguration config = new PropertiesConfiguration(filename);   
  80.         KeyFactory keyFactory = KeyFactory.getInstance("RSA",   
  81.                 new BouncyCastleProvider());   
  82.   
  83.         if (type == 0) {   
  84.             // privateKey   
  85.             String privateKeyValue = config.getString("PULIICKEY");   
  86.             PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(   
  87.                     toBytes(privateKeyValue));   
  88.             PrivateKey privateKey = keyFactory.generatePrivate(priPKCS8);   
  89.             return privateKey;   
  90.   
  91.         } else {   
  92.             // publicKey   
  93.             String privateKeyValue = config.getString("PRIVATEKEY");   
  94.             X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(   
  95.                     toBytes(privateKeyValue));   
  96.             PublicKey publicKey = keyFactory.generatePublic(bobPubKeySpec);   
  97.             return publicKey;   
  98.         }   
  99.     }   
  100.   
  101.     /**  
  102.      * Encrypt String.  
  103.      *   
  104.      * @return byte[]  
  105.      */  
  106.     protected byte[] encrypt(RSAPublicKey publicKey, byte[] data) {   
  107.         if (publicKey != null) {   
  108.             try {   
  109.                 Cipher cipher = Cipher.getInstance("RSA",   
  110.                         new BouncyCastleProvider());   
  111.                 cipher.init(Cipher.ENCRYPT_MODE, publicKey);   
  112.                 return cipher.doFinal(data);   
  113.             } catch (Exception e) {   
  114.                 e.printStackTrace();   
  115.             }   
  116.         }   
  117.         return null;   
  118.     }   
  119.   
  120.     /**  
  121.      * Basic decrypt method  
  122.      *   
  123.      * @return byte[]  
  124.      */  
  125.     protected byte[] decrypt(RSAPrivateKey privateKey, byte[] raw) {   
  126.         if (privateKey != null) {   
  127.             try {   
  128.                 Cipher cipher = Cipher.getInstance("RSA",   
  129.                         new BouncyCastleProvider());   
  130.                 cipher.init(Cipher.DECRYPT_MODE, privateKey);   
  131.                 return cipher.doFinal(raw);   
  132.             } catch (Exception e) {   
  133.                 e.printStackTrace();   
  134.             }   
  135.         }   
  136.   
  137.         return null;   
  138.     }   
  139.   
  140.     public static String toHexString(byte[] b) {   
  141.         StringBuilder sb = new StringBuilder(b.length * 2);   
  142.         for (int i = 0; i < b.length; i++) {   
  143.             sb.append(HEXCHAR[(b[i] & 0xf0) >>> 4]);   
  144.             sb.append(HEXCHAR[b[i] & 0x0f]);   
  145.         }   
  146.         return sb.toString();   
  147.     }   
  148.   
  149.     public static final byte[] toBytes(String s) {   
  150.         byte[] bytes;   
  151.         bytes = new byte[s.length() / 2];   
  152.         for (int i = 0; i < bytes.length; i++) {   
  153.             bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2),   
  154.                     16);   
  155.         }   
  156.         return bytes;   
  157.     }   
  158.   
  159.     private static char[] HEXCHAR = { '0', '1', '2', '3', '4', '5', '6', '7',   
  160.             '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };   
  161.   
  162. }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
RSA是一种非对称加密算法,它可以用于对文件进行加密解密。在Java中,可以使用Java的加密库来实现RSA加密解密。下面是一个简单的示例代码: ```java import java.io.*; import java.security.*; import javax.crypto.*; public class RSAEncryption { private static final String PUBLIC_KEY_FILE = "public.key"; private static final String PRIVATE_KEY_FILE = "private.key"; public static void main(String[] args) throws Exception { // 生成对 KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); keyGen.initialize(1024, random); KeyPair keyPair = keyGen.generateKeyPair(); // 保存和私文件 saveKeyToFile(keyPair.getPublic(), PUBLIC_KEY_FILE); saveKeyToFile(keyPair.getPrivate(), PRIVATE_KEY_FILE); // 加密文件 encryptFile("plaintext.txt", "ciphertext.txt", keyPair.getPublic()); // 解密文件 decryptFile("ciphertext.txt", "decrypted.txt", keyPair.getPrivate()); } private static void saveKeyToFile(Key key, String fileName) throws IOException { byte[] keyBytes = key.getEncoded(); FileOutputStream fos = new FileOutputStream(fileName); fos.write(keyBytes); fos.close(); } private static void encryptFile(String inputFile, String outputFile, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); byte[] buffer = new byte[100]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { byte[] output = cipher.update(buffer, 0, bytesRead); if (output != null) { fos.write(output); } } byte[] output = cipher.doFinal(); if (output != null) { fos.write(output); } fis.close(); fos.flush(); fos.close(); } private static void decryptFile(String inputFile, String outputFile, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); byte[] buffer = new byte[128]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { byte[] output = cipher.update(buffer, 0, bytesRead); if (output != null) { fos.write(output); } } byte[] output = cipher.doFinal(); if (output != null) { fos.write(output); } fis.close(); fos.flush(); fos.close(); } } ``` 上面的代码中,首先生成对,然后保存和私文件中。接着,使用公对明文文件进行加密,将保存文件中。最后,使用私文件进行解密,将明文保存文件中。 需要注意的是,RSA算法只能加密长度小的数据,因此在加密文件时,需要将文件分块加密,并将每个加密保存文件中。在解密时,将每个加密读取出来,进行解密,然后将解密结果拼接起来即可。 另外,由于RSA算法的加密解密速度比较慢,因此在加密文件时,可能需要使用其他加密算法,如AES算法,来加密文件

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值