Dazed and confused by Java Security & BouncyCastle APIs

后端 未结 3 466
太阳男子
太阳男子 2021-01-31 11:57

I\'ve been trying to make sense of the BouncyCastle cryptography APIs for Java. Unfortunately, I\'m finding Java cryptography in general to be so obscured by service provider in

3条回答
  •  盖世英雄少女心
    2021-01-31 12:37

    import java.security.GeneralSecurityException;
    import java.security.KeyFactory;
    import java.security.KeyPairGenerator;
    import java.security.PublicKey;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    
    import javax.crypto.Cipher;
    
    public class RsaCrypto {
    
        private static final int KEY_SIZE = 3072;
        private static final String TRANSFORMATION = "RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING";
    
        public static KeyPair generateRSAKeyPair() {
            try {
                KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
                gen.initialize(KEY_SIZE);
                java.security.KeyPair p = gen.generateKeyPair();
                KeyPair pair = new KeyPair();
                pair.privateKey = p.getPrivate().getEncoded();
                pair.publicKey = p.getPublic().getEncoded();
                return pair;
            } catch (GeneralSecurityException e) {
                throw new RuntimeException(e);
            }
    
        }
    
        public static byte[] encrypt(byte[] data, byte[] publicKey) {
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
            try {
                KeyFactory kf = KeyFactory.getInstance("RSA");
                PublicKey pk = kf.generatePublic(publicKeySpec);
                Cipher rsa = Cipher.getInstance(TRANSFORMATION);
                rsa.init(Cipher.ENCRYPT_MODE, pk);
                return rsa.doFinal(data);
            } catch (GeneralSecurityException e) {
                throw new RuntimeException(e);
            }
        }
    
        public static byte[] decrypt(byte[] encryptedData, byte[] privateKey) {
            try {
                PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privateKey);
                RSAPrivateKey pk = (RSAPrivateKey) KeyFactory.getInstance("RSA")
                        .generatePrivate(privSpec);
    
                Cipher rsaCipher = Cipher.getInstance(TRANSFORMATION);
                rsaCipher.init(Cipher.DECRYPT_MODE, pk);
                return rsaCipher.doFinal(encryptedData);
    
            } catch (GeneralSecurityException e) {
                throw new RuntimeException(e);
            }
        }
    
    }
    

提交回复
热议问题