公钥加密也称为非对称加密、速度慢、加密和解密的钥匙不相同,某一个人持有私钥,任何人都可以知道公钥
- package com.stone.security;
-
- import java.security.KeyPair;
- import java.security.KeyPairGenerator;
- import java.security.PrivateKey;
- import java.security.PublicKey;
- import java.util.Arrays;
-
- import javax.crypto.Cipher;
-
- public class RSA {
- public static final String KEY_ALGORITHM = "RSA";
- public static final String CIPHER_ALGORITHM_ECB1 = "RSA/ECB/PKCS1Padding";
- public static final String CIPHER_ALGORITHM_ECB2 = "RSA/ECB/OAEPWithSHA-1AndMGF1Padding";
- public static final String CIPHER_ALGORITHM_ECB3 = "OAEPWithSHA-256AndMGF1Padding";
-
- static PublicKey publicKey;
- static PrivateKey privateKey;
- static Cipher cipher;
- static KeyPair keyPair;
-
- public static void main(String[] args) throws Exception {
- method1("斯柯达U*(Sfsad7f()*^%%$");
- method2("斯柯达U*(Sfsad7f()*^%%$");
- method3("斯柯达U*(Sfsad7f()*^%%$");
-
- }
-
-
- static void method1(String str) throws Exception {
- KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
- KeyPair keyPair = keyGenerator.generateKeyPair();
- publicKey = keyPair.getPublic();
- privateKey = keyPair.getPrivate();
- cipher = Cipher.getInstance(KEY_ALGORITHM);
- cipher.init(Cipher.ENCRYPT_MODE, publicKey);
- byte[] encrypt = cipher.doFinal(str.getBytes());
- System.out.println("公钥加密后1:" + Arrays.toString(encrypt));
-
- cipher.init(Cipher.DECRYPT_MODE, privateKey);
- byte[] decrypt = cipher.doFinal(encrypt);
- System.out.println("私钥解密后1:" + new String(decrypt));
- }
-
-
- static void method2(String str) throws Exception {
- KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
- KeyPair keyPair = keyGenerator.generateKeyPair();
- publicKey = keyPair.getPublic();
- privateKey = keyPair.getPrivate();
- cipher = Cipher.getInstance(KEY_ALGORITHM);
- cipher.init(Cipher.ENCRYPT_MODE, privateKey);
- byte[] encrypt = cipher.doFinal(str.getBytes());
- System.out.println("私钥加密后2:" + Arrays.toString(encrypt));
-
- cipher.init(Cipher.DECRYPT_MODE, publicKey);
- byte[] decrypt = cipher.doFinal(encrypt);
- System.out.println("公钥解密后2:" + new String(decrypt));
- }
-
-
- static void method3(String str) throws Exception {
- KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
- KeyPair keyPair = keyGenerator.generateKeyPair();
- publicKey = keyPair.getPublic();
- privateKey = keyPair.getPrivate();
- cipher = Cipher.getInstance(CIPHER_ALGORITHM_ECB1);
- cipher.init(Cipher.ENCRYPT_MODE, privateKey);
- byte[] encrypt = cipher.doFinal(str.getBytes());
- System.out.println("私钥加密后3:" + Arrays.toString(encrypt));
-
- cipher.init(Cipher.DECRYPT_MODE, publicKey);
- byte[] decrypt = cipher.doFinal(encrypt);
- System.out.println("公钥解密后3:" + new String(decrypt));
- }
- }