java rsa私钥加密

Python019

java rsa私钥加密,第1张

java rsa私钥加密是什么?让我们一起来了解一下吧!

java rsa私钥加密是一种加密算法。私钥加密算法是用私钥来进行加密与解密信息。私钥加密也被称作对称加密,原因是加密与解密使用的秘钥是同一个。

RSA加密需要注意的事项如下:

1. 首先产生公钥与私钥

2. 设计加密与解密的算法

3. 私钥加密的数据信息只能由公钥可以解密

4. 公钥加密的数据信息只能由私钥可以解密

实战演练,具体步骤如下: public class RsaCryptTools {     private static final String CHARSET = "utf-8"     private static final Base64.Decoder decoder64 = Base64.getDecoder()     private static final Base64.Encoder encoder64 = Base64.getEncoder()       /**      * 生成公私钥      * @param keySize      * @return      * @throws NoSuchAlgorithmException      */     public static SecretKey generateSecretKey(int keySize) throws NoSuchAlgorithmException {         //生成密钥对         KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA")         keyGen.initialize(keySize, new SecureRandom())         KeyPair pair = keyGen.generateKeyPair()         PrivateKey privateKey = pair.getPrivate()         PublicKey publicKey = pair.getPublic()         //这里可以将密钥对保存到本地         return new SecretKey(encoder64.encodeToString(publicKey.getEncoded()), encoder64.encodeToString(privateKey.getEncoded()))     }     /**      * 私钥加密      * @param data      * @param privateInfoStr      * @return      * @throws IOException      * @throws InvalidCipherTextException      */     public static String encryptData(String data, String privateInfoStr) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {           Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")         cipher.init(Cipher.ENCRYPT_MODE, getPrivateKey(privateInfoStr))         return encoder64.encodeToString(cipher.doFinal(data.getBytes(CHARSET)))     }       /**      * 公钥解密      * @param data      * @param publicInfoStr      * @return      */     public static String decryptData(String data, String publicInfoStr) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {         byte[] encryptDataBytes=decoder64.decode(data.getBytes(CHARSET))         //解密         Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")         cipher.init(Cipher.DECRYPT_MODE, getPublicKey(publicInfoStr))         return new String(cipher.doFinal(encryptDataBytes), CHARSET)     }     private static PublicKey getPublicKey(String base64PublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey.getBytes()))         KeyFactory keyFactory = KeyFactory.getInstance("RSA")         return keyFactory.generatePublic(keySpec)     }     private static PrivateKey getPrivateKey(String base64PrivateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {         PrivateKey privateKey = null         PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64PrivateKey.getBytes()))         KeyFactory keyFactory = null         keyFactory = KeyFactory.getInstance("RSA")         privateKey = keyFactory.generatePrivate(keySpec)         return privateKey     }       /**      * 密钥实体      * @author hank      * @since 2020/2/28 0028 下午 16:27      */     public static class SecretKey {         /**          * 公钥          */         private String publicKey         /**          * 私钥          */         private String privateKey           public SecretKey(String publicKey, String privateKey) {             this.publicKey = publicKey             this.privateKey = privateKey         }           public String getPublicKey() {             return publicKey         }           public void setPublicKey(String publicKey) {             this.publicKey = publicKey         }           public String getPrivateKey() {             return privateKey         }           public void setPrivateKey(String privateKey) {             this.privateKey = privateKey         }           @Override         public String toString() {             return "SecretKey{" +                     "publicKey='" + publicKey + '\'' +                     ", privateKey='" + privateKey + '\'' +                     '}'         }     }       private static void writeToFile(String path, byte[] key) throws IOException {         File f = new File(path)         f.getParentFile().mkdirs()           try(FileOutputStream fos = new FileOutputStream(f)) {             fos.write(key)             fos.flush()         }     }       public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, IOException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, InvalidKeySpecException {         SecretKey secretKey = generateSecretKey(2048)         System.out.println(secretKey)         String enStr = encryptData("你好测试测试", secretKey.getPrivateKey())         System.out.println(enStr)         String deStr = decryptData(enStr, secretKey.getPublicKey())         System.out.println(deStr)         enStr = encryptData("你好测试测试hello", secretKey.getPrivateKey())         System.out.println(enStr)         deStr = decryptData(enStr, secretKey.getPublicKey())         System.out.println(deStr)     }   }

下面是RSA加密代码。

/**

* RSA算法,实现数据的加密解密。

* @author ShaoJiang

*

*/

public class RSAUtil {

private static Cipher cipher

static{

try {

cipher = Cipher.getInstance("RSA")

} catch (NoSuchAlgorithmException e) {

e.printStackTrace()

} catch (NoSuchPaddingException e) {

e.printStackTrace()

}

}

/**

* 生成密钥对

* @param filePath 生成密钥的路径

* @return

*/

public static Map<String,String>generateKeyPair(String filePath){

try {

KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA")

// 密钥位数

keyPairGen.initialize(1024)

// 密钥对

KeyPair keyPair = keyPairGen.generateKeyPair()

// 公钥

PublicKey publicKey = (RSAPublicKey) keyPair.getPublic()

// 私钥

PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate()

//得到公钥字符串

String publicKeyString = getKeyString(publicKey)

//得到私钥字符串

String privateKeyString = getKeyString(privateKey)

FileWriter pubfw = new FileWriter(filePath+"/publicKey.keystore")

FileWriter prifw = new FileWriter(filePath+"/privateKey.keystore")

BufferedWriter pubbw = new BufferedWriter(pubfw)

BufferedWriter pribw = new BufferedWriter(prifw)

pubbw.write(publicKeyString)

pribw.write(privateKeyString)

pubbw.flush()

pubbw.close()

pubfw.close()

pribw.flush()

pribw.close()

prifw.close()

//将生成的密钥对返回

Map<String,String>map = new HashMap<String,String>()

map.put("publicKey",publicKeyString)

map.put("privateKey",privateKeyString)

return map

} catch (Exception e) {

e.printStackTrace()

}

return null

}

/**

* 得到公钥

*

* @param key

*密钥字符串(经过base64编码)

* @throws Exception

*/

public static PublicKey getPublicKey(String key) throws Exception {

byte[] keyBytes

keyBytes = (new BASE64Decoder()).decodeBuffer(key)

X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes)

KeyFactory keyFactory = KeyFactory.getInstance("RSA")

PublicKey publicKey = keyFactory.generatePublic(keySpec)

return publicKey

}

/**

* 得到私钥

*

* @param key

*密钥字符串(经过base64编码)

* @throws Exception

*/

public static PrivateKey getPrivateKey(String key) throws Exception {

byte[] keyBytes

keyBytes = (new BASE64Decoder()).decodeBuffer(key)

PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes)

KeyFactory keyFactory = KeyFactory.getInstance("RSA")

PrivateKey privateKey = keyFactory.generatePrivate(keySpec)

return privateKey

}

/**

* 得到密钥字符串(经过base64编码)

*

* @return

*/

public static String getKeyString(Key key) throws Exception {

byte[] keyBytes = key.getEncoded()

String s = (new BASE64Encoder()).encode(keyBytes)

return s

}

/**

* 使用公钥对明文进行加密,返回BASE64编码的字符串

* @param publicKey

* @param plainText

* @return

*/

public static String encrypt(PublicKey publicKey,String plainText){

try {

cipher.init(Cipher.ENCRYPT_MODE, publicKey)

byte[] enBytes = cipher.doFinal(plainText.getBytes())

return (new BASE64Encoder()).encode(enBytes)

} catch (InvalidKeyException e) {

e.printStackTrace()

} catch (IllegalBlockSizeException e) {

e.printStackTrace()

} catch (BadPaddingException e) {

e.printStackTrace()

}

return null

}

/**

* 使用keystore对明文进行加密

* @param publicKeystore 公钥文件路径

* @param plainText 明文

* @return

*/

public static String encrypt(String publicKeystore,String plainText){

try {

FileReader fr = new FileReader(publicKeystore)

BufferedReader br = new BufferedReader(fr)

String publicKeyString=""

String str

while((str=br.readLine())!=null){

publicKeyString+=str

}

br.close()

fr.close()

cipher.init(Cipher.ENCRYPT_MODE,getPublicKey(publicKeyString))

byte[] enBytes = cipher.doFinal(plainText.getBytes())

return (new BASE64Encoder()).encode(enBytes)

} catch (InvalidKeyException e) {

e.printStackTrace()

} catch (IllegalBlockSizeException e) {

e.printStackTrace()

} catch (BadPaddingException e) {

e.printStackTrace()

} catch (Exception e) {

e.printStackTrace()

}

return null

}

/**

* 使用私钥对明文密文进行解密

* @param privateKey

* @param enStr

* @return

*/

public static String decrypt(PrivateKey privateKey,String enStr){

try {

cipher.init(Cipher.DECRYPT_MODE, privateKey)

byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr))

return new String(deBytes)

} catch (InvalidKeyException e) {

e.printStackTrace()

} catch (IllegalBlockSizeException e) {

e.printStackTrace()

} catch (BadPaddingException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

}

return null

}

/**

* 使用keystore对密文进行解密

* @param privateKeystore 私钥路径

* @param enStr 密文

* @return

*/

public static String decrypt(String privateKeystore,String enStr){

try {

FileReader fr = new FileReader(privateKeystore)

BufferedReader br = new BufferedReader(fr)

String privateKeyString=""

String str

while((str=br.readLine())!=null){

privateKeyString+=str

}

br.close()

fr.close()

cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKeyString))

byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr))

return new String(deBytes)

} catch (InvalidKeyException e) {

e.printStackTrace()

} catch (IllegalBlockSizeException e) {

e.printStackTrace()

} catch (BadPaddingException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

} catch (Exception e) {

e.printStackTrace()

}

return null

}

}