概要
cscの作法、調べてみた。
BouncyCastle.Crypto.dll使ってみた。
練習問題やってみた。
練習問題
暗号を復号せよ。
方針
平文は、「hogehoge2」。
rsaで作る。
秘密鍵、公開鍵の両方で、やる。
サンプルコード
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Operators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Encodings;
namespace ConsoleExample
{
class Program {
static void Main(string[] args) {
var myenc = File.ReadAllText("myenc.txt");
var encrypted = Convert.FromBase64String(myenc);
var privateKeyPem = new StreamReader(@"myprivatekey.pem", Encoding.ASCII);
var privateKeyReader = new PemReader(privateKeyPem);
var keyPair = (AsymmetricCipherKeyPair) privateKeyReader.ReadObject();
var rsa = new Pkcs1Encoding(new RsaEngine());
rsa.Init(false, keyPair.Private);
byte[] decrypted = rsa.ProcessBlock(encrypted, 0, encrypted.Length);
Console.WriteLine("decrypted: " + Encoding.UTF8.GetString(decrypted));
var myenc2 = File.ReadAllText("myenc2.txt");
var encrypted2 = Convert.FromBase64String(myenc2);
var publicKeyPem = new StreamReader(@"mypublickey.pem", Encoding.ASCII);
var publicKeyReader = new PemReader(publicKeyPem);
var publicKeyParam = (AsymmetricKeyParameter) publicKeyReader.ReadObject();
var rsa2 = new Pkcs1Encoding(new RsaEngine());
rsa2.Init(false, publicKeyParam);
byte[] decrypted2 = rsa2.ProcessBlock(encrypted2, 0, encrypted.Length);
Console.WriteLine("decrypted: " + Encoding.UTF8.GetString(decrypted2));
}
}
}
実行結果
>bc11
decrypted: hogehoge2
decrypted: hogehoge2
以上。