Skip to content

Instantly share code, notes, and snippets.

@eaba
Created March 11, 2020 07:19
Show Gist options
  • Select an option

  • Save eaba/e52fea4304d3c9ce5a0942e5cc1cf4e0 to your computer and use it in GitHub Desktop.

Select an option

Save eaba/e52fea4304d3c9ce5a0942e5cc1cf4e0 to your computer and use it in GitHub Desktop.

Revisions

  1. @saldoukhov saldoukhov created this gist Dec 7, 2016.
    22 changes: 22 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    RsaKeyPairGenerator r = new RsaKeyPairGenerator();
    r.Init(new KeyGenerationParameters(prng, 2048));
    AsymmetricCipherKeyPair keys = r.GenerateKeyPair();
    SubjectPublicKeyInfo pubF = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keys.Public);
    byte[] pubbytes = pubF.GetDerEncoded();
    PrivateKeyInfo privF = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keys.Private);
    byte[] privBytes = privF.GetDerEncoded();

    // encrypt with public
    SubjectPublicKeyInfo pbInfo = SubjectPublicKeyInfo.GetInstance(pubbytes);
    AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(pbInfo);
    IAsymmetricBlockCipher encryptEngine = new RsaEngine();
    encryptEngine.Init(true, pubKey);
    byte[] dt = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    byte[] encDt = encryptEngine.ProcessBlock(dt, 0, dt.Length);

    // decrypt with private
    PrivateKeyInfo pkInfo = PrivateKeyInfo.GetInstance(privBytes);
    AsymmetricKeyParameter privateKey = PrivateKeyFactory.CreateKey(pkInfo);
    IAsymmetricBlockCipher decryptEngine = new RsaEngine();
    decryptEngine.Init(false, privateKey);
    byte[] decDt = decryptEngine.ProcessBlock(encDt, 0, encDt.Length);