internal override void Evaluate() { byte[] oaepOut = Hex.Decode( "4458cce0f94ebd79d275a134d224f95ef4126034e5d979359703b466096fcc15b71b78df4d4a68033112dfcfad7611cc" + "0458475ab4a66b815f87fcb16a8aa1133441b9d61ed846c4856c5d42059fab7505bd8ffa5281a2bb187c6c853f298c98" + "d5752a40be905f85e5ccb27d59415f09ac12a1788d654c675d98f412e6481e6f1159f1736dd96b29c99b411b4e5420b5" + "6b07be2885dbc397fa091f66877c41e502cb4afeba460a2ebcdec7d09d933e630b98a4510ad6f32ca7ffc1bdb43e46ff" + "f709819d3a69d9b62b774cb12c9dc176a6911bf370ab5029719dc1b4c13e23e57e46a7cd8ba5ee54c954ed460835ddab" + "0086fa36ac110a5790e82c929bc7ca86"); IAsymmetricBlockCipher cipher = new OaepEncoding(provider.CreateEngine(EngineUsage.GENERAL), new Sha1Digest(), new Sha1Digest(), null); cipher.Init(true, new ParametersWithRandom(testPubKey, new TestRandomData("18b776ea21069d69776a33e96bad48e1dda0a5ef"))); byte[] output; output = cipher.ProcessBlock(msg, 0, msg.Length); if (!Arrays.AreEqual(FipsKats.Values[FipsKats.Vec.RsaStartupOaepEnc], output)) { Fail("self test OAEP transport encrypt failed."); } cipher.Init(false, new ParametersWithRandom(testPrivKey, Utils.testRandom)); output = cipher.ProcessBlock(oaepOut, 0, oaepOut.Length); if (!Arrays.AreEqual(FipsKats.Values[FipsKats.Vec.RsaStartupOaepDec], output)) { Fail("self test OAEP transport decrypt failed."); } }
public void Test_Function() { SHA256Managed hash = new SHA256Managed(); SecureRandom randomNumber = new SecureRandom(); byte[] encodingParam = hash.ComputeHash(Encoding.UTF8.GetBytes(randomNumber.ToString())); string inputMessage = "Test Message"; UTF8Encoding utf8enc = new UTF8Encoding(); byte[] inputBytes = utf8enc.GetBytes(inputMessage); RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator(); rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 1024)); AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair(); publicKey = (RsaKeyParameters)keyPair.Public; privateKey = (RsaKeyParameters)keyPair.Private; //string pub = GetPublicKey(); //string priv = GetPrivateKey(); IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest(), encodingParam); cipher.Init(true, publicKey); byte[] ciphered = cipher.ProcessBlock(inputBytes, 0, inputMessage.Length); string cipheredText = utf8enc.GetString(ciphered); cipher.Init(false, privateKey); byte[] deciphered = cipher.ProcessBlock(ciphered, 0, ciphered.Length); string decipheredText = utf8enc.GetString(deciphered); }
private void EncDec( string label, RsaKeyParameters pubParameters, RsaKeyParameters privParameters, byte[] seed, byte[] input, byte[] output) { IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine()); cipher.Init(true, new ParametersWithRandom(pubParameters, new VecRand(seed))); byte[] outBytes = cipher.ProcessBlock(input, 0, input.Length); for (int i = 0; i != output.Length; i++) { if (outBytes[i] != output[i]) { Fail(label + " failed encryption"); } } cipher.Init(false, privParameters); outBytes = cipher.ProcessBlock(output, 0, output.Length); for (int i = 0; i != input.Length; i++) { if (outBytes[i] != input[i]) { Fail(label + " failed decoding"); } } }
private void doTestOaep(RsaKeyParameters pubParameters, RsaKeyParameters privParameters) { // // OAEP - public encrypt, private decrypt // IAsymmetricBlockCipher eng = new OaepEncoding(new RsaEngine()); byte[] data = Hex.Decode(input); eng.Init(true, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, privParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed OAEP Test"); } // check for oversized input byte[] message = new byte[87]; RsaEngine rsaEngine = new RsaEngine(); IAsymmetricBlockCipher cipher = new OaepEncoding(rsaEngine, new Sha1Digest(), new Sha1Digest(), message); cipher.Init(true, new ParametersWithRandom(pubParameters, new SecureRandom())); try { cipher.ProcessBlock(message, 0, message.Length); Fail("no exception thrown"); } catch (DataLengthException e) { IsTrue("message mismatch", "input data too long".Equals(e.Message)); } catch (InvalidCipherTextException e) { Fail("failed - exception " + e.ToString(), e); } }
internal static string Decode(string data) { try { X509Certificate k; // read in the certificate using (var textReader = File.OpenText("public.cer")) { // I'm assuming here that the certificate is PEM-encoded. var pemReader = new PemReader(textReader); k = (X509Certificate)pemReader.ReadObject(); } // un-base64 the input var dataBytes = Convert.FromBase64String(data); // what php openssl_public_decrypt does var cipher = new OaepEncoding(new RsaEngine()); cipher.Init(false, k.GetPublicKey()); var returnBytes = cipher.ProcessBlock(dataBytes, 0, dataBytes.Length); // What is the character-encoding of the bytes? UTF-8? return(Encoding.UTF8.GetString(returnBytes)); } catch (Exception ex) { return("Failed:" + ex.Message); } }
private static void DecryptRsa(Stream input, Stream output, Stream key, byte[] salt, char[] password) { using (StreamReader streamReader = new StreamReader(key)) { AsymmetricCipherKeyPair cipherKeyPair = (AsymmetricCipherKeyPair) new PemReader(streamReader, new PasswordFinder(password)).ReadObject(); using (MemoryStream inputMemory = new MemoryStream(), outputMemory = new MemoryStream()) { input.CopyTo(inputMemory); byte[] inputBytes = inputMemory.ToArray(); IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest(), salt); cipher.Init(false, cipherKeyPair.Private); int length = inputBytes.Length; int blockSize = cipher.GetInputBlockSize(); for (int offset = 0; offset < length; offset += blockSize) { int chunkSize = Math.Min(blockSize, length - offset); byte[] deciphered = cipher.ProcessBlock(inputBytes, offset, chunkSize); outputMemory.Write(deciphered, 0, deciphered.Length); } outputMemory.WriteTo(output); Console.WriteLine("RSA-OAEP decryption successfull."); } } }
public static string RSADecrypt(string cipherText, string pri) { byte[] cipherTextBytes = Convert.FromBase64String(cipherText); StringReader t = new StringReader(pri); PemReader pr = new PemReader(t); AsymmetricCipherKeyPair keys = (AsymmetricCipherKeyPair)pr.ReadObject(); OaepEncoding eng = new OaepEncoding(new RsaEngine()); eng.Init(false, keys.Private); int length = cipherTextBytes.Length; int blockSize = eng.GetInputBlockSize(); List <byte> plainTextBytes = new List <byte>(); for (int chunkPosition = 0; chunkPosition < length; chunkPosition += blockSize) { int chunkSize = Math.Min(blockSize, length - chunkPosition); plainTextBytes.AddRange(eng.ProcessBlock( cipherTextBytes, chunkPosition, chunkSize )); } string st = Encoding.UTF8.GetString(plainTextBytes.ToArray()); return(st); }
/// <summary> /// Decrypts the specified encrypted e-KYC response data received from UIDAI. /// </summary> /// <param name="kycInfo">The encrypted e-KYC data.</param> /// <returns>The decrypted e-KYC data.</returns> /// <exception cref="ArgumentNullException"><paramref name="kycInfo"/> or <see cref="EncryptedKycInfo.InfoValue"/> is null.</exception> public DecryptedKycInfo Decrypt(EncryptedKycInfo kycInfo) { ValidateNull(kycInfo, nameof(kycInfo)); ValidateNull(kycInfo.InfoValue, nameof(EncryptedKycInfo.InfoValue)); var iv = new byte[kycInfo.OaepLabel.Count]; Buffer.BlockCopy(kycInfo.OaepLabel.Array, kycInfo.OaepLabel.Offset, iv, 0, iv.Length); // Decrypt Key var oaep = new OaepEncoding(new RsaEngine(), new Sha256Digest(), iv); oaep.Init(false, DotNetUtilities.GetRsaKeyPair(KuaKey.GetRSAPrivateKey()).Private); var key = oaep.ProcessBlock(kycInfo.EncryptedKey.Array, kycInfo.EncryptedKey.Offset, kycInfo.EncryptedKey.Count); // Decrypt Data var cipher = CipherUtilities.GetCipher(SymmetricAlgorithm); var parameter = new ParametersWithIV(new KeyParameter(key), iv, 0, 16); cipher.Init(false, parameter); var data = cipher.DoFinal(kycInfo.EncryptedData.Array, kycInfo.EncryptedData.Offset, kycInfo.EncryptedData.Count); return(new DecryptedKycInfo { InfoValue = data }); }
public static byte[] Encrypt(byte[] data, byte[] key) { var pr = new PemReader(new StringReader(StringHelper.NewString(key).Trim())); var keys = (RsaKeyParameters)pr.ReadObject(); // Pure mathematical RSA implementation // RsaEngine eng = new RsaEngine(); // PKCS1 v1.5 paddings // Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine()); // PKCS1 OAEP paddings var eng = new OaepEncoding(new RsaEngine()); eng.Init(true, keys); var length = data.Length; var blockSize = eng.GetInputBlockSize(); var encryptedData = new List <byte>(); for (var chunkPosition = 0; chunkPosition < length; chunkPosition += blockSize) { var chunkSize = Math.Min(blockSize, length - chunkPosition); encryptedData.AddRange(eng.ProcessBlock(data, chunkPosition, chunkSize)); } return(encryptedData.ToArray()); }
/// <summary> /// Uses RSA Publickey to Ecrypt /// Requires .pem file /// </summary> /// <param name="plainText"></param> /// <returns>Cypherbasestring</returns> protected internal static string Encrypt(string plainText) { byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); Org.BouncyCastle.OpenSsl.PemReader pr = new Org.BouncyCastle.OpenSsl.PemReader( File.OpenText(Program.tempDirectory + "\\IAPubkey.pem") ); RsaKeyParameters keys = (RsaKeyParameters)pr.ReadObject(); // PKCS1 OAEP paddings OaepEncoding eng = new OaepEncoding(new RsaEngine()); eng.Init(true, keys); // Pure mathematical RSA implementation int length = plainTextBytes.Length; int blockSize = eng.GetInputBlockSize(); List <byte> cipherTextBytes = new List <byte>(); for (int chunkPosition = 0; chunkPosition < length; chunkPosition += blockSize) { int chunkSize = Math.Min(blockSize, length - chunkPosition); cipherTextBytes.AddRange(eng.ProcessBlock( plainTextBytes, chunkPosition, chunkSize )); } return(Convert.ToBase64String(cipherTextBytes.ToArray())); }
public void btn_enc_Ok_Click(object sender, EventArgs e) { bool isChecked_enc = rb_enc_pri.Checked; //Encryption using private key if (isChecked_enc) { IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine()); cipher.Init(true, GprivateKey); // byte[] ciphertext = System.Text.Encoding.UTF8.GetBytes(txt_enc_writeText.Text); byte[] plaintext = System.Text.Encoding.UTF8.GetBytes(txt_enc_writeText.Text); byte[] ciphertext = cipher.ProcessBlock(plaintext, 0, plaintext.Length); string result = Encoding.UTF8.GetString(ciphertext); txt_enc_output.Text = result; //txt_enc_output.Text = System.Text.Encoding.UTF8.GetString(ciphertext); } //encryption using public key else { IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine()); cipher.Init(true, GpublicKey); // byte[] ciphertext = System.Text.Encoding.UTF8.GetBytes(txt_enc_writeText.Text); byte[] plaintext = System.Text.Encoding.UTF8.GetBytes(txt_enc_writeText.Text); byte[] ciphertext = cipher.ProcessBlock(plaintext, 0, plaintext.Length); string result = Encoding.UTF8.GetString(ciphertext); txt_enc_output.Text = result; } }
public string Decrypt(string encryptedText, string certificateKey, string privateCertificateFile) { try { byte[] cipherTextBytes = Convert.FromBase64String(encryptedText); IPasswordFinder pf = new securityPasswordFinderInterface(certificateKey); PemReader pr = new PemReader( (StreamReader)File.OpenText(privateCertificateFile), pf ); AsymmetricCipherKeyPair keys = (AsymmetricCipherKeyPair)pr.ReadObject(); OaepEncoding eng = new OaepEncoding(new RsaEngine()); eng.Init(false, keys.Private); int length = cipherTextBytes.Length; int blockSize = eng.GetInputBlockSize(); List <byte> plainTextBytes = new List <byte>(); for (int chunkPosition = 0; chunkPosition < length; chunkPosition += blockSize) { int chunkSize = Math.Min(blockSize, length - chunkPosition); plainTextBytes.AddRange(eng.ProcessBlock( cipherTextBytes, chunkPosition, chunkSize )); } return(Encoding.UTF8.GetString(plainTextBytes.ToArray())); } catch (Exception ex) { throw ex; } }
public byte[] Decrypt(byte[] data) { if (_keyPrivate == null) { throw new Exception("Private key not set"); } var engine = new OaepEncoding(new RsaEngine()); engine.Init(false, _keyPrivate); int length = data.Length; int blockSize = engine.GetInputBlockSize(); var decryptedBytes = new List <byte>(); for (int chunkPosition = 0; chunkPosition < length; chunkPosition += blockSize) { int chunkSize = Math.Min(blockSize, length - chunkPosition); decryptedBytes.AddRange(engine.ProcessBlock( data, chunkPosition, chunkSize )); } return(decryptedBytes.ToArray()); }
public static string DecryptRsa(byte[] encrypted, string key, Encoding encoding) { using (var privateKeyPem = new StringReader(key)) { var rsa = new OaepEncoding(new RsaEngine()); var privateKeyReader = new PemReader(privateKeyPem); var keyPair = (AsymmetricCipherKeyPair)privateKeyReader.ReadObject(); rsa.Init(false, keyPair.Private); var blockDataSize = rsa.GetInputBlockSize(); var decrypted = encrypted .Buffer(blockDataSize) .Select(x => { var arr = x.ToArray(); return(rsa.ProcessBlock(arr, 0, arr.Length)); }) .SelectMany(x => x) .ToArray(); return(encoding.GetString(decrypted)); } }
public static byte[] EncryptRsa(string plainText, string key, Encoding encoding) { using (var publicKeyPem = new StringReader(key)) { var publicKeyReader = new PemReader(publicKeyPem); var publicKeyParam = (AsymmetricKeyParameter)publicKeyReader.ReadObject(); var rsa = new OaepEncoding(new RsaEngine()); rsa.Init(true, publicKeyParam); var blockDataSize = rsa.GetInputBlockSize(); var encrypted = encoding .GetBytes(plainText) .Buffer(blockDataSize) .Select(x => { var arr = x.ToArray(); return(rsa.ProcessBlock(arr, 0, arr.Length)); }) .SelectMany(x => x) .ToArray(); return(encrypted); } }
/* * Function: EncryptByPublicKey() * Key Type: PEM * Description: Encrypt data by public key, corresponding to function DecryptByPrivateKey() */ public static string EncryptByPublicKey(string plainText, string publicKey, string paddingMode) { byte[] plainByte = Encoding.UTF8.GetBytes(plainText); IAsymmetricBlockCipher encoding; switch (paddingMode) { case MessageDefinition.RSAPaddingMode01: encoding = new Pkcs1Encoding(new RsaEngine()); break; case MessageDefinition.RSAPaddingMode02: encoding = new ISO9796d1Encoding(new RsaEngine()); break; default: encoding = new OaepEncoding(new RsaEngine()); break; } encoding.Init(true, ReadPublicKey(publicKey)); int blockSize = encoding.GetInputBlockSize(); List <byte> output = new List <byte>(); for (int chunkPositon = 0; chunkPositon < plainByte.Length; chunkPositon += blockSize) { int chunkSize = Math.Min(blockSize, plainByte.Length - chunkPositon); output.AddRange(encoding.ProcessBlock(plainByte, chunkPositon, chunkSize)); } return(Convert.ToBase64String(output.ToArray())); }
private static byte[] DecodeSymmetricKey(string label, string privateKeyPath, string ciphertext) { byte[] cipherTextBytes = HexToByte(ciphertext); byte[] labelBytes = Encoding.UTF8.GetBytes(label); PemReader pr = new PemReader(File.OpenText(privateKeyPath)); AsymmetricCipherKeyPair keys = (AsymmetricCipherKeyPair)pr.ReadObject(); OaepEncoding eng = new OaepEncoding(new RsaEngine(), new Sha256Digest(), new Sha256Digest(), labelBytes); eng.Init(false, keys.Private); int length = cipherTextBytes.Length; int blockSize = eng.GetInputBlockSize(); List <byte> plainTextBytes = new List <byte>(); for (int chunkPosition = 0; chunkPosition < length; chunkPosition += blockSize) { int chunkSize = Math.Min(blockSize, length - chunkPosition); plainTextBytes.AddRange(eng.ProcessBlock( cipherTextBytes, chunkPosition, chunkSize )); } return(plainTextBytes.ToArray()); }
public static string RSAEncryptLong(string XmlPublicKey, string PlainText) { byte[] publicInfoByte = Convert.FromBase64String(XmlPublicKey); AsymmetricKeyParameter publicKey = PublicKeyFactory.CreateKey(publicInfoByte); var decryptEngine = new OaepEncoding(new RsaEngine()); decryptEngine.Init(true, publicKey); byte[] bytesToDecrypt = Encoding.Default.GetBytes(PlainText); int MaxPlainTextLength = Common.GetOEAPFixedMaxPlainTextLength(decryptEngine.GetOutputBlockSize()); byte[] decrypted = null; int Times = (bytesToDecrypt.Length - 1) / MaxPlainTextLength + 1; List <byte> encryptedCache = new List <byte>(); int Counter = 0; while (Counter < Times) { int RemainLength = bytesToDecrypt.Length - MaxPlainTextLength * Counter; int Length = MaxPlainTextLength > RemainLength ? RemainLength : MaxPlainTextLength; byte[] decryptedPatch = decryptEngine.ProcessBlock(bytesToDecrypt, MaxPlainTextLength * Counter, Length); encryptedCache.AddRange(decryptedPatch); Counter++; } decrypted = encryptedCache.ToArray(); return(Convert.ToBase64String(decrypted)); }
public static byte[] Decrypt(byte[] data, byte[] key, byte[] encodingParam) { var pr = new PemReader(new StringReader(StringHelper.NewString(key).Trim())); var keys = (AsymmetricCipherKeyPair)pr.ReadObject(); // Pure mathematical RSA implementation // RsaEngine eng = new RsaEngine(); // PKCS1 v1.5 paddings // Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine()); // PKCS1 OAEP paddings var eng = new OaepEncoding(new RsaEngine(), new Sha256Digest(), encodingParam); eng.Init(false, keys.Private); var length = data.Length; var blockSize = eng.GetInputBlockSize(); var decryptedData = new List <byte>(); for (var chunkPosition = 0; chunkPosition < length; chunkPosition += blockSize) { var chunkSize = Math.Min(blockSize, length - chunkPosition); decryptedData.AddRange(eng.ProcessBlock(data, chunkPosition, chunkSize)); } return(decryptedData.ToArray()); }
// to be done public static string RSADecryptLong(string XmlPrivateKey, string EncryptedText) { AsymmetricKeyParameter privateKey = PrivateKeyFactory.CreateKey(Convert.FromBase64String(XmlPrivateKey)); var decryptEngine = new OaepEncoding(new RsaEngine()); decryptEngine.Init(false, privateKey); int CipherLength = decryptEngine.GetInputBlockSize(); byte[] bytesToDecrypt = Convert.FromBase64String(EncryptedText); byte[] decrypted = null; int Times = (bytesToDecrypt.Length - 1) / CipherLength + 1; List <byte> decryptedCache = new List <byte>(); int Counter = 0; while (Counter < Times) { byte[] decryptedPatch = decryptEngine.ProcessBlock(bytesToDecrypt, CipherLength * Counter, CipherLength); decryptedCache.AddRange(decryptedPatch); Counter++; } decrypted = decryptedCache.ToArray(); return(Encoding.Default.GetString(decrypted)); }
/// <summary> /// Create instance of RSAManager /// </summary> public RSAManager RSAGenerateManager() { var keyGen = new RsaKeyPairGenerator(); keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); var keyPair = keyGen.GenerateKeyPair(); Func <string, string> decrypt = (string encryptedValue) => { var decryptEngine = new OaepEncoding(new RsaEngine()); var bytesToDecrypt = Convert.FromBase64String(encryptedValue); decryptEngine.Init(false, keyPair.Private as RsaPrivateCrtKeyParameters); return(Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length))); }; var info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); var stringWriter = new StringWriter(); var pemWriter = new PemWriter(stringWriter); var pemObject = new PemObject("PUBLIC KEY", info.GetEncoded()); pemWriter.WriteObject(pemObject); return(new RSAManager { Decrypt = decrypt, PublicKey = stringWriter.ToString(), }); }
public static byte[] Decrypt(byte[] data, AsymmetricKeyParameter key) { var cipher = new OaepEncoding(new RsaEngine()); cipher.Init(false, key); return(cipher.ProcessBlock(data, 0, data.Length)); }
internal static void PostProcess(this IEncryptedPrivateKeyModel model, string secretCryptoAccessKey) { // reference: https://stackoverflow.com/questions/44767290/decrypt-passphrase-protected-pem-containing-private-key using (var keyReader = new StringReader(model.EncryptedPrivateKey)) { // decrypt server-provided PEM private key using our secret passphrase var pemReader = new PemReader(keyReader, new PasswordFinder(secretCryptoAccessKey)); object privateKeyObject = pemReader.ReadObject(); var rsaPrivatekey = privateKeyObject as RsaPrivateCrtKeyParameters; if (rsaPrivatekey != null) { var rsaEngine = new OaepEncoding( new RsaEngine(), new Sha1Digest(), new Sha1Digest(), null); rsaEngine.Init(false, rsaPrivatekey); // use the client's private key to decrypt the server-provided data key, // storing the result in the 'UnwrappedDataKey' property var wrappedDataKeyBytes = Convert.FromBase64String(model.WrappedDataKey); model.UnwrappedDataKey = rsaEngine.ProcessBlock(wrappedDataKeyBytes, 0, wrappedDataKeyBytes.Length); } } }
/// <summary> /// Encrypts the data with RSA oaep SHA 512 /// </summary> /// <param name="key">The RSA public keys</param> /// <param name="data">Data to encrypt</param> /// <returns>Encrypted data</returns> public static byte[] RsaEncrypt(AsymmetricKeyParameter key, byte[] data) { var encryptEngine = new OaepEncoding(new RsaEngine(), new Sha512Digest()); encryptEngine.Init(true, key); return(encryptEngine.ProcessBlock(data, 0, data.Length)); }
public static string RSAEncrypt(string plainText, string pub) { byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); StringReader t = new StringReader(pub); PemReader pr = new PemReader(t); RsaKeyParameters keys = (RsaKeyParameters)pr.ReadObject(); OaepEncoding eng = new OaepEncoding(new RsaEngine()); eng.Init(true, keys); int length = plainTextBytes.Length; int blockSize = eng.GetInputBlockSize(); List <byte> cipherTextBytes = new List <byte>(); for (int chunkPosition = 0; chunkPosition < length; chunkPosition += blockSize) { int chunkSize = Math.Min(blockSize, length - chunkPosition); cipherTextBytes.AddRange(eng.ProcessBlock( plainTextBytes, chunkPosition, chunkSize )); } return(Convert.ToBase64String(cipherTextBytes.ToArray())); }
/// <summary> /// Encrypts a file key. /// </summary> /// <param name="plainFileKey">The file key to encrypt.</param> /// <param name="userPublicKey">The public key which should be used for the encryption.</param> /// <returns>The encrypted file key.</returns> /// <exception cref="Dracoon.Crypto.Sdk.InvalidFileKeyException">If the provided file key is invalid.</exception> /// <exception cref="Dracoon.Crypto.Sdk.InvalidKeyPairException">If the provided public key is invalid.</exception> /// <exception cref="Dracoon.Crypto.Sdk.CryptoException">If an unexpected error occured.</exception> public static EncryptedFileKey EncryptFileKey(PlainFileKey plainFileKey, UserPublicKey userPublicKey) { ValidatePlainFileKey(plainFileKey); ValidateUserPublicKey(userPublicKey); AsymmetricKeyParameter pubKey = ConvertPublicKey(userPublicKey.PublicKey); byte[] eFileKey; try { OaepEncoding engine = new OaepEncoding(new RsaEngine(), new Sha256Digest(), new Sha1Digest(), null); engine.Init(true, pubKey); byte[] pFileKey = Convert.FromBase64String(plainFileKey.Key); eFileKey = engine.ProcessBlock(pFileKey, 0, pFileKey.Length); } catch (Exception e) { throw new CryptoException("Could not encrypt file key. Encryption failed.", e); } EncryptedFileKey encFileKey = new EncryptedFileKey() { Key = Convert.ToBase64String(eFileKey), Iv = plainFileKey.Iv, Tag = plainFileKey.Tag, Version = plainFileKey.Version }; return(encFileKey); }
private static byte[] Process(byte[] data, AsymmetricKeyParameter key, bool isEncryption) { var encoding = new OaepEncoding(new RsaEngine(), new Sha256Digest(), new Sha1Digest(), new byte[0]); encoding.Init(isEncryption, key); return(encoding.ProcessBlock(data, 0, data.Length)); }
/// <summary> /// Decrypts a file key. /// </summary> /// <param name="encFileKey">The file key to decrypt.</param> /// <param name="userPrivateKey">The private key which should be used for the decryption.</param> /// <param name="password">The password which secures the private key.</param> /// <returns>The decrypted file key.</returns> /// <exception cref="Dracoon.Crypto.Sdk.InvalidFileKeyException">If the provided encrypted file key is invalid.</exception> /// <exception cref="Dracoon.Crypto.Sdk.InvalidKeyPairException">If the provided private key is invalid.</exception> /// <exception cref="Dracoon.Crypto.Sdk.InvalidPasswordException">If the provided private key password is invalid</exception> /// <exception cref="Dracoon.Crypto.Sdk.CryptoException">If an unexpected error in the decryption occured.</exception> public static PlainFileKey DecryptFileKey(EncryptedFileKey encFileKey, UserPrivateKey userPrivateKey, string password) { ValidateEncryptedFileKey(encFileKey); ValidateUserPrivateKey(userPrivateKey); ValidatePassword(password); AsymmetricKeyParameter privateKey = DecryptPrivateKey(userPrivateKey.PrivateKey, password); byte[] dFileKey; try { OaepEncoding engine = new OaepEncoding(new RsaEngine(), new Sha256Digest(), new Sha1Digest(), null); engine.Init(false, privateKey); byte[] eFileKey = Convert.FromBase64String(encFileKey.Key); dFileKey = engine.ProcessBlock(eFileKey, 0, eFileKey.Length); } catch (InvalidCipherTextException e) { throw new CryptoException("Could not decrypt file key. Decryption failed.", e); } PlainFileKey plainFileKey = new PlainFileKey() { Key = Convert.ToBase64String(dFileKey), Iv = encFileKey.Iv, Tag = encFileKey.Tag, Version = encFileKey.Version }; return(plainFileKey); }
static void Main(string[] args) { // Console.WriteLine("Hello World!"); // Variables declaration string SrcData; byte[] tmpSource; // byte[] tempHash; // Retrieve message Console.WriteLine("Ingrese cualquier texto: "); SrcData = Console.ReadLine(); // Create byte array from source data tmpSource = Encoding.ASCII.GetBytes(SrcData); Console.WriteLine(); Console.WriteLine("Pareja de llaves generandose...\n"); // RSAKeyPairGenerator RsaKeyPairGenerator rsaKeyPairGen = new RsaKeyPairGenerator(); rsaKeyPairGen.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); AsymmetricCipherKeyPair keyPair = rsaKeyPairGen.GenerateKeyPair(); // Extract public and private key RsaKeyParameters PrivateKey = (RsaKeyParameters)keyPair.Private; RsaKeyParameters PublicKey = (RsaKeyParameters)keyPair.Public; // Print public key in PEM format TextWriter textWriter1 = new StringWriter(); PemWriter pemWriter1 = new PemWriter(textWriter1); pemWriter1.WriteObject(PublicKey); pemWriter1.Writer.Flush(); string printPublicKey = textWriter1.ToString(); Console.WriteLine("La llave pública es: {0}", printPublicKey); Console.WriteLine(); // Encryption IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine()); cipher.Init(true, PublicKey); byte[] cipherText = cipher.ProcessBlock(tmpSource, 0, tmpSource.Length); string result = Encoding.UTF8.GetString(cipherText); Console.WriteLine("Texto cifrado: "); Console.WriteLine(result); Console.WriteLine(); Console.WriteLine("¿Quiete descifrar el texto? Presione espacio para cifrarlo, o cualquier otra tecla si no"); char inputChar = Console.ReadKey().KeyChar; if (inputChar == ' ') { Decryption(cipherText, PrivateKey); } }
private byte[] get_encrypted_session_key(byte[] session_key) { int length = session_key.Length; RsaKeyParameters keys = settings.get_public_key(); // Pure mathematical RSA implementation // RsaEngine eng = new RsaEngine(); // PKCS1 v1.5 paddings // Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine()); // PKCS1 OAEP paddings OaepEncoding eng = new OaepEncoding(new RsaEngine()); eng.Init(true, keys); int blockSize = eng.GetInputBlockSize(); List <byte> cipherTextBytes = new List <byte>(); for (int chunkPosition = 0; chunkPosition < length; chunkPosition += blockSize) { int chunkSize = Math.Min(blockSize, length - chunkPosition); cipherTextBytes.AddRange(eng.ProcessBlock( session_key, chunkPosition, chunkSize )); } return(cipherTextBytes.ToArray()); }