Dazed and confused by Java Security & BouncyCastle APIs

后端 未结 3 599
太阳男子
太阳男子 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:47

    import java.security.GeneralSecurityException;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    
    import javax.crypto.Cipher;
    
    public class RSACrypto
    {
    
      /* A 1024-bit key will encrypt messages up to 117 bytes long. */
      private static final int KEY_SIZE = 1024;
    
      private static final String XFORM = 
        "RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING";
    
      public static KeyPair generateRSAKeyPair()
        throws GeneralSecurityException
      {
        KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
        gen.initialize(KEY_SIZE);
        return gen.generateKeyPair();
      }
    
      public static byte[] encrypt(byte[] plaintext, PublicKey pub)
        throws GeneralSecurityException
      {
        Cipher cipher = Cipher.getInstance(XFORM);
        cipher.init(Cipher.ENCRYPT_MODE, pub);
        return cipher.doFinal(plaintext);
      }
    
      public static byte[] decrypt(byte[] ciphertext, PrivateKey pvt)
        throws GeneralSecurityException
      {
        Cipher cipher = Cipher.getInstance(XFORM);
        cipher.init(Cipher.DECRYPT_MODE, pvt);
        return cipher.doFinal(ciphertext);
      }
    
      public static void main(String... argv)
        throws Exception
      {
        KeyPair pair = RSACrypto.generateRSAKeyPair();
        byte[] plaintext = "A short secret message.".getBytes("UTF-8");
        byte[] ciphertext = RSACrypto.encrypt(plaintext, pair.getPublic());
        byte[] recovered = RSACrypto.decrypt(ciphertext, pair.getPrivate());
        System.out.println(new String(recovered, "UTF-8"));
      }
    
    }
    

提交回复
热议问题