public string aesEncode(string plainText) { byte[] plainBytes = Byte_Transform.GetBytes(plainText); byte[] outputBytes = new byte[aesCipher.GetOutputSize(plainBytes.Length)]; aesCipher.Reset(); aesCipher.Init(true, cipherParameters); int length = aesCipher.ProcessBytes(plainBytes, outputBytes, 0); aesCipher.DoFinal(outputBytes, length); //Do the final block return(Convert.ToBase64String(outputBytes)); }
public IMessage Encrypt(Boolean normal, byte[] data, out byte[] outdata) { IMessage msg = new TextMessage("Error.Unknown"); outdata = new byte[1]; switch (this.Type) { case "RSA": try { SecureRandom rand = new SecureRandom(); IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA1AndMGF1Padding"); if (normal == true) { cipher.Init(true, new ParametersWithRandom(this.PublicKey, rand)); } else { cipher.Init(true, new ParametersWithRandom(this.PrivateKey, rand)); } byte[] cipherTextBlock = null; int outputsize = cipher.GetOutputSize(data.Length); //Array size of ciphered data (encrypted data) int blockSize = cipher.GetBlockSize(); //Amount of data we can process at one time (-2 -2*hlen) List <byte> output = new List <byte>(); int outputLen = 0; byte[] dataToProcess = null; for (int chunkPosition = 0; chunkPosition < data.Length; chunkPosition += blockSize) { dataToProcess = new byte[blockSize]; int chunkSize = (data.Length - chunkPosition) < blockSize ? (data.Length - chunkPosition) : blockSize; //Math.Min(blockSize, data.Length - (chunkPosition * blockSize)); Buffer.BlockCopy(data, chunkPosition, dataToProcess, 0, chunkSize); cipherTextBlock = new byte[outputsize]; outputLen = cipher.ProcessBytes(dataToProcess, 0, chunkSize, cipherTextBlock, 0); cipher.DoFinal(cipherTextBlock, outputLen); //output.AddRange(e.ProcessBytes(data, chunkPosition, // chunkSize)); output.AddRange(cipherTextBlock); } outdata = output.ToArray(); msg.Type = "Error.OK"; } catch { } break; } return(msg); }
/// <summary> /// Finishes this instance. /// </summary> /// <exception cref="InvalidCryptoDataException"></exception> public override void Finish() { try { Init(); var buffLen = _cipher.GetOutputSize(_inLen) - _outLen; var buffer = new byte[buffLen]; var writeLen = _cipher.DoFinal(buffer, 0); _output.Write(buffer, 0, writeLen); buffer.Clear(); } catch (InvalidCipherTextException ex) { throw new InvalidCryptoDataException(ex.Message); } }
public string Decrypt(string data) { byte[] dataAsBytes = Hex.Decode(data); byte[] keyAsBytes = System.Text.Encoding.Default.GetBytes(DecryptKey); int inputLength = dataAsBytes.Length; IBufferedCipher bf = CipherUtilities.GetCipher("Blowfish/ECB/PKCS5Padding"); KeyParameter key = new KeyParameter(keyAsBytes); bf.Init(false, key); byte[] output = new byte[bf.GetOutputSize(inputLength)]; int outputLength = bf.ProcessBytes(dataAsBytes, output, 0); bf.DoFinal(output, outputLength); string final = System.Text.Encoding.ASCII.GetString(output); return(final); }
public byte[] EnDecrypt(bool forEncrypt, byte[] inBytes) { cipher = CipherUtilities.GetCipher(algorithm); cipher.Init(forEncrypt, key); int outBytesSize = cipher.GetOutputSize(inBytes.Length); byte[] outBytes = new byte[outBytesSize]; int outLentgh; outLentgh = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); outLentgh += cipher.DoFinal(outBytes, outLentgh); if (outLentgh != outBytesSize) { return null; } return outBytes; }
private static byte[] DoCryptStuff(byte[] data, IKey key, CipherDirection direction, CipherMode cipherMode, byte[] iv) { byte[] result; String transformation = key.GetAlgorithm(); if (key.GetAlgorithm().StartsWith(ALG_DES)) { transformation += "/" + ModetoString(cipherMode) + "/" + DES_NO_PADDING; } ICipherParameters keyparam = new KeyParameter(key.GetEncoded()); IBufferedCipher cipher = CipherUtilities.GetCipher(transformation); if (cipherMode != CipherMode.ECB) { keyparam = new ParametersWithIV(keyparam, iv); } byte[] output = new byte[cipher.GetOutputSize(data.Length)]; cipher.Init(direction == CipherDirection.ENCRYPT_MODE ? true : false, keyparam); result = cipher.DoFinal(data); if (cipherMode != CipherMode.ECB) { Array.Copy(result, result.Length - 8, iv, 0, iv.Length); } //AlgorithmParameterSpec aps = null; //try //{ // Cipher c1 = Cipher.getInstance(transformation, provider.getName()); // if (cipherMode != CipherMode.ECB) // aps = new IvParameterSpec(iv); // c1.init(direction, key, aps); // result = c1.doFinal(data); // if (cipherMode != CipherMode.ECB) // System.arraycopy(result, result.length - 8, iv, 0, iv.length); //} //catch (Exception e) //{ // throw e; //} return(result); }
/* * This method performs all the decryption and writes * the plain text to the buffered output stream created * previously. */ static public string Decode(string encyStr, string key, string iv) { /* * Setup the DES cipher engine, with PKCS5PADDING * in CBC mode. */ if (cipher == null) { cipher = CipherUtilities.GetCipher("DES/CBC/PKCS5PADDING"); } string result = null; byte[] key_ = Encoding.UTF8.GetBytes(key.Substring(0, 8)); byte[] iv_ = Encoding.UTF8.GetBytes(iv.Substring(0, 8)); cipher.Init(false, new ParametersWithIV(new DesParameters(key_), iv_)); try { int outL = 0; byte[] outblock = null; string decodeUrl = Uri.UnescapeDataString(encyStr); byte[] inblock = Convert.FromBase64String(decodeUrl); outblock = new byte[cipher.GetOutputSize(inblock.Length)]; outL = cipher.ProcessBytes(inblock, 0, inblock.Length, outblock, 0); /* * Before we write anything out, we need to make sure * that we've got something to write out. */ if (outL > 0) { cipher.DoFinal(outblock, outL); } result = Encoding.UTF8.GetString(outblock, 0, outblock.Length); } catch (IOException) { } return(result); }
/// <summary> /// Finishes this instance. /// </summary> public override void Finish() { if (!_init && _encrypt) { if (!CipherTextOnly) { _output.Write(_iv, 0, _iv.Length); } _initFunc(_iv, _cipher, _encrypt); _init = true; } var buffLen = _cipher.GetOutputSize(_inLen) - _outLen; var buffer = new byte[buffLen]; var writeLen = _cipher.DoFinal(buffer, 0); _output.Write(buffer, 0, writeLen); buffer.Clear(); }
private static EncryptionResult EncryptMessage(byte[] userKey, byte[] userSecret, byte[] data, ushort padding = 0, bool randomisePadding = false) { SecureRandom random = new SecureRandom(); byte[] salt = new byte[16]; random.NextBytes(salt); X9ECParameters curve = ECNamedCurveTable.GetByName("prime256v1"); ECDomainParameters spec = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed()); ECKeyPairGenerator generator = new ECKeyPairGenerator(); generator.Init(new ECKeyGenerationParameters(spec, new SecureRandom())); AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair(); ECDHBasicAgreement agreementGenerator = new ECDHBasicAgreement(); agreementGenerator.Init(keyPair.Private); BigInteger ikm = agreementGenerator.CalculateAgreement(new ECPublicKeyParameters(spec.Curve.DecodePoint(userKey), spec)); byte[] prk = GenerateHkdf(userSecret, ikm.ToByteArrayUnsigned(), Encoding.UTF8.GetBytes("Content-Encoding: auth\0"), 32); byte[] publicKey = ((ECPublicKeyParameters)keyPair.Public).Q.GetEncoded(false); byte[] cek = GenerateHkdf(salt, prk, CreateInfoChunk("aesgcm", userKey, publicKey), 16); byte[] nonce = GenerateHkdf(salt, prk, CreateInfoChunk("nonce", userKey, publicKey), 12); if (randomisePadding && padding > 0) { padding = Convert.ToUInt16(Math.Abs(random.NextInt()) % (padding + 1)); } byte[] input = new byte[padding + 2 + data.Length]; Buffer.BlockCopy(ConvertInt(padding), 0, input, 0, 2); Buffer.BlockCopy(data, 0, input, padding + 2, data.Length); IBufferedCipher cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding"); cipher.Init(true, new AeadParameters(new KeyParameter(cek), 128, nonce)); byte[] message = new byte[cipher.GetOutputSize(input.Length)]; cipher.DoFinal(input, 0, input.Length, message, 0); return(new EncryptionResult() { Salt = salt, Payload = message, PublicKey = publicKey }); }
/// <summary> /// Transforms the specified region of the specified byte array. /// </summary> /// <param name="inputBuffer">The input for which to compute the transform.</param> /// <param name="inputOffset">The offset into the byte array from which to begin using data.</param> /// <param name="inputCount">The number of bytes in the byte array to use as data.</param> /// <returns> /// The computed transform. /// </returns> /// <exception cref="System.Security.Cryptography.CryptographicException">Implementation only supports whole block processing and ECB.</exception> public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { try { byte[] final = new byte[_cipher.GetOutputSize(inputCount)]; int len = _cipher.ProcessBytes(inputBuffer, inputOffset, inputCount, final, 0); len += _cipher.DoFinal(final, len); if (len != final.Length) { byte[] shorter = new byte[len]; Array.Copy(final, 0, shorter, 0, len); final = shorter; } _cipher.Reset(); return(final); } catch (CryptoException ce) { throw new Core.Runtime.CryptoException("Error in cryptographic transformation.", ErrorStatus.CryptographicError, ce); } }
public static EncryptionResult EncryptMessage(byte[] userKey, byte[] userSecret, byte[] data, ushort padding = 0, bool randomisePadding = false) { SecureRandom Random = new SecureRandom(); byte[] Salt = new byte[16]; Random.NextBytes(Salt); X9ECParameters Curve = ECNamedCurveTable.GetByName("prime256v1"); ECDomainParameters Spec = new ECDomainParameters(Curve.Curve, Curve.G, Curve.N, Curve.H, Curve.GetSeed()); ECKeyPairGenerator Generator = new ECKeyPairGenerator(); Generator.Init(new ECKeyGenerationParameters(Spec, new SecureRandom())); AsymmetricCipherKeyPair KeyPair = Generator.GenerateKeyPair(); ECDHBasicAgreement AgreementGenerator = new ECDHBasicAgreement(); AgreementGenerator.Init(KeyPair.Private); BigInteger IKM = AgreementGenerator.CalculateAgreement(new ECPublicKeyParameters(Spec.Curve.DecodePoint(userKey), Spec)); byte[] PRK = GenerateHKDF(userSecret, IKM.ToByteArrayUnsigned(), Encoding.UTF8.GetBytes("Content-Encoding: auth\0"), 32); byte[] PublicKey = ((ECPublicKeyParameters)KeyPair.Public).Q.GetEncoded(false); byte[] CEK = GenerateHKDF(Salt, PRK, CreateInfoChunk("aesgcm", userKey, PublicKey), 16); byte[] Nonce = GenerateHKDF(Salt, PRK, CreateInfoChunk("nonce", userKey, PublicKey), 12); if (randomisePadding && padding > 0) { padding = Convert.ToUInt16(Math.Abs(Random.NextInt()) % (padding + 1)); } byte[] Input = new byte[padding + 2 + data.Length]; Buffer.BlockCopy(ConvertInt(padding), 0, Input, 0, 2); Buffer.BlockCopy(data, 0, Input, padding + 2, data.Length); IBufferedCipher Cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding"); Cipher.Init(true, new AeadParameters(new KeyParameter(CEK), 128, Nonce)); byte[] Message = new byte[Cipher.GetOutputSize(Input.Length)]; Cipher.DoFinal(Input, 0, Input.Length, Message, 0); return(new EncryptionResult() { Salt = Salt, Payload = Message, PublicKey = PublicKey }); }
public int GetMaxOutputSize(int inputLen) { return(cipher.GetOutputSize(inputLen)); }
private void doTestGP( int size, int privateValueSize, BigInteger g, BigInteger p) { IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ElGamal"); // DHParameterSpec elParams = new DHParameterSpec(p, g); // keyGen.initialize(elParams); ElGamalParameters elParams = new ElGamalParameters(p, g, privateValueSize); ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters( new SecureRandom(), elParams); keyGen.Init(elKgp); AsymmetricCipherKeyPair keyPair = keyGen.GenerateKeyPair(); SecureRandom rand = new SecureRandom(); checkKeySize(privateValueSize, keyPair); IBufferedCipher cipher = CipherUtilities.GetCipher("ElGamal"); cipher.Init(true, new ParametersWithRandom(keyPair.Public, rand)); byte[] inBytes = Encoding.ASCII.GetBytes("This is a test"); if (cipher.GetOutputSize(inBytes.Length) != (size / 8) * 2) { Fail("getOutputSize wrong on encryption"); } byte[] outBytes = cipher.DoFinal(inBytes); cipher.Init(false, keyPair.Private); if (cipher.GetOutputSize(outBytes.Length) != (size / 8) - 1) { Fail("GetOutputSize wrong on decryption"); } // // No Padding - maximum length // byte[] modBytes = ((ElGamalPublicKeyParameters)keyPair.Public).Parameters.P.ToByteArray(); byte[] maxInput = new byte[modBytes.Length - 1]; maxInput[0] |= 0x7f; cipher.Init(true, new ParametersWithRandom(keyPair.Public, rand)); outBytes = cipher.DoFinal(maxInput); cipher.Init(false, keyPair.Private); outBytes = cipher.DoFinal(outBytes); if (!AreEqual(outBytes, maxInput)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(maxInput) + " got " + Hex.ToHexString(outBytes)); } // // encrypt/decrypt // IBufferedCipher c1 = CipherUtilities.GetCipher("ElGamal"); IBufferedCipher c2 = CipherUtilities.GetCipher("ElGamal"); c1.Init(true, new ParametersWithRandom(keyPair.Public, rand)); byte[] out1 = c1.DoFinal(inBytes); c2.Init(false, keyPair.Private); byte[] out2 = c2.DoFinal(out1); if (!AreEqual(inBytes, out2)) { Fail(size + " encrypt test failed"); } // // encrypt/decrypt with update // int outLen = c1.ProcessBytes(inBytes, 0, 2, out1, 0); outLen += c1.DoFinal(inBytes, 2, inBytes.Length - 2, out1, outLen); outLen = c2.ProcessBytes(out1, 0, 2, out2, 0); outLen += c2.DoFinal(out1, 2, out1.Length - 2, out2, outLen); if (!AreEqual(inBytes, out2)) { Fail(size + " encrypt with update test failed"); } // // public key encoding test // // byte[] pubEnc = keyPair.Public.GetEncoded(); byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public).GetDerEncoded(); // KeyFactory keyFac = KeyFactory.GetInstance("ElGamal"); // X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); // DHPublicKeyParameters pubKey = (DHPublicKeyParameters)keyFac.generatePublic(pubX509); ElGamalPublicKeyParameters pubKey = (ElGamalPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc); ElGamalParameters spec = pubKey.Parameters; if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P)) { Fail(size + " bit public key encoding/decoding test failed on parameters"); } if (!((ElGamalPublicKeyParameters)keyPair.Public).Y.Equals(pubKey.Y)) { Fail(size + " bit public key encoding/decoding test failed on y value"); } /* * // * // public key serialisation test * // * // TODO Is there some standard this serialization must conform to? * BinaryFormatter formatter = new BinaryFormatter(); * * MemoryStream bOut = new MemoryStream(); * // ObjectOutputStream oOut = new ObjectOutputStream(bOut); * // oOut.writeObject(keyPair.Public); * formatter.Serialize(bOut, keyPair.Public); * * MemoryStream bIn = new MemoryStream(bOut.ToArray(), false); * // ObjectInputStream oIn = new ObjectInputStream(bIn); * // pubKey = (DHPublicKeyParameters)oIn.readObject(); * pubKey = (ElGamalPublicKeyParameters) formatter.Deserialize(bIn); * spec = pubKey.Parameters; * * if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P)) * { * Fail(size + " bit public key serialisation test failed on parameters"); * } * * if (!((ElGamalPublicKeyParameters )keyPair.Public).Y.Equals(pubKey.Y)) * { * Fail(size + " bit public key serialisation test failed on y value"); * } */ // // private key encoding test // // TODO Keys don't support GetEncoded // byte[] privEnc = keyPair.Private.GetEncoded(); byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private).GetDerEncoded(); // PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); // DHPrivateKeyParameters privKey = (DHPrivateKeyParameters)keyFac.generatePrivate(privPKCS8); ElGamalPrivateKeyParameters privKey = (ElGamalPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc); spec = privKey.Parameters; if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P)) { Fail(size + " bit private key encoding/decoding test failed on parameters"); } if (!((ElGamalPrivateKeyParameters)keyPair.Private).X.Equals(privKey.X)) { Fail(size + " bit private key encoding/decoding test failed on y value"); } /* * // * // private key serialisation test * // * bOut = new MemoryStream(); * // oOut = new ObjectOutputStream(bOut); * // oOut.writeObject(keyPair.Private); * formatter.Serialize(bOut, keyPair.Private); * * bIn = new MemoryStream(bOut.ToArray(), false); * // oIn = new ObjectInputStream(bIn); * // privKey = (DHPrivateKeyParameters)oIn.readObject(); * privKey = (ElGamalPrivateKeyParameters) formatter.Deserialize(bIn); * spec = privKey.Parameters; * * if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P)) * { * Fail(size + " bit private key serialisation test failed on parameters"); * } * * if (!((ElGamalPrivateKeyParameters) keyPair.Private).X.Equals(privKey.X)) * { * Fail(size + " bit private key serialisation test failed on y value"); * } */ }
public int GetMaxOutputSize(int inputLen) { return(bufferedCipher.GetOutputSize(inputLen)); }