java rsa私钥加密

Python012

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)     }   }

加密解密并非java才有的,所有编程语言都有加密和解密。

目前的加密解密主要可分为以下2大类:

对称秘钥加密:如DES算法,3DES算法,TDEA算法,Blowfish算法,RC5算法,IDEA算法等。其主要特点是加密方和解密方都有同一个密码,加密方和解密方可以使用秘钥任意加密解密。

非对称密码加密:这种加密方式加密方仅有加密秘钥,对加密后的密文无法反向解密,解密方仅有解密秘钥,无法对明文进行加密。

另外还有一些摘要算法,比如MD5和HASH此类算法不可逆,但经常用来作为确认字段或者对一些重要匹配信息签名防止明文内容被修改。

基本的单向加密算法:

BASE64 严格地说,属于编码格式,而非加密算法

MD5(Message Digest algorithm 5,信息摘要算法)

SHA(Secure Hash Algorithm,安全散列算法)

HMAC(Hash Message Authentication Code,散列消息鉴别码)

复杂的对称加密(DES、PBE)、非对称加密算法:

DES(Data Encryption Standard,数据加密算法)

PBE(Password-based encryption,基于密码验证)

RSA(算法的名字以发明者的名字命名:Ron Rivest, AdiShamir 和Leonard Adleman)

DH(Diffie-Hellman算法,密钥一致协议)

DSA(Digital Signature Algorithm,数字签名)

ECC(Elliptic Curves Cryptography,椭圆曲线密码编码学)

代码参考:

/**

* BASE64加密

*

* @param key

* @return

* @throws Exception

*/

public static String encryptBASE64(byte[] key) throws Exception {

return (new BASE64Encoder()).encodeBuffer(key)

}

/**

* MD5加密

*

* @param data

* @return

* @throws Exception

*/

public static byte[] encryptMD5(byte[] data) throws Exception {

MessageDigest md5 = MessageDigest.getInstance(KEY_MD5)

md5.update(data)

return md5.digest()

}

/**

* SHA加密

*

* @param data

* @return

* @throws Exception

*/

public static byte[] encryptSHA(byte[] data) throws Exception {

MessageDigest sha = MessageDigest.getInstance(KEY_SHA)

sha.update(data)

return sha.digest()

}

}

/**

* 初始化HMAC密钥

*

* @return

* @throws Exception

*/

public static String initMacKey() throws Exception {

KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC)

SecretKey secretKey = keyGenerator.generateKey()

return encryptBASE64(secretKey.getEncoded())

}

/**

* HMAC加密

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static byte[] encryptHMAC(byte[] data, String key) throws Exception {

SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC)

Mac mac = Mac.getInstance(secretKey.getAlgorithm())

mac.init(secretKey)

return mac.doFinal(data)

}