public LoRaPayloadJoinAccept(byte[] inputMessage, string appKey) { // Only MHDR is not encrypted with the key // ( PHYPayload = MHDR[1] | MACPayload[..] | MIC[4] ) this.Mhdr = new Memory<byte>(inputMessage, 0, 1); // Then we will take the rest and decrypt it // DecryptPayload(inputMessage); // var decrypted = PerformEncryption(appKey); // Array.Copy(decrypted, 0, inputMessage, 0, decrypted.Length); // DecryptPayload(inputMessage); AesEngine aesEngine = new AesEngine(); var key = ConversionHelper.StringToByteArray(appKey); aesEngine.Init(true, new KeyParameter(key)); Aes aes = new AesManaged { Key = key, IV = new byte[16], Mode = CipherMode.ECB, Padding = PaddingMode.None }; ICryptoTransform cipher; cipher = aes.CreateEncryptor(); byte[] pt = new byte[inputMessage.Length - 1]; Array.Copy(inputMessage, 1, pt, 0, pt.Length); // Array.Reverse(pt); var decryptedPayload = cipher.TransformFinalBlock(pt, 0, pt.Length); // We will copy back in the main inputMessage the content Array.Copy(decryptedPayload, 0, inputMessage, 1, decryptedPayload.Length); // ( MACPayload = AppNonce[3] | NetID[3] | DevAddr[4] | DLSettings[1] | RxDelay[1] | CFList[0|15] ) var appNonce = new byte[3]; Array.Copy(inputMessage, 1, appNonce, 0, 3); Array.Reverse(appNonce); this.AppNonce = new Memory<byte>(appNonce); var netID = new byte[3]; Array.Copy(inputMessage, 4, netID, 0, 3); Array.Reverse(netID); this.NetID = new Memory<byte>(netID); var devAddr = new byte[4]; Array.Copy(inputMessage, 7, devAddr, 0, 4); Array.Reverse(devAddr); this.DevAddr = new Memory<byte>(devAddr); var dlSettings = new byte[1]; Array.Copy(inputMessage, 11, dlSettings, 0, 1); this.DlSettings = new Memory<byte>(dlSettings); var rxDelay = new byte[1]; Array.Copy(inputMessage, 11, rxDelay, 0, 1); this.RxDelay = new Memory<byte>(rxDelay); // It's the configuration list, it can be empty or up to 15 bytes // - 17 = - 1 - 3 - 3 - 4 - 1 - 1 - 4 // This is the size of all mandatory elements of the message var cfList = new byte[inputMessage.Length - 17]; Array.Copy(inputMessage, 12, cfList, 0, inputMessage.Length - 17); Array.Reverse(cfList); this.CfList = new Memory<byte>(cfList); var mic = new byte[4]; Array.Copy(inputMessage, inputMessage.Length - 4, mic, 0, 4); this.Mic = new Memory<byte>(mic); }
/// <summary> /// Symmetrical encryption of the bytes /// </summary> /// <param name="key">Password for the encryption</param> /// <param name="bytes">Bytes array which should be encrypted</param> /// <returns></returns> public static byte[] EncryptBytes(byte[] key, byte[] secret, byte[] iv = null) { var iv_base64 = string.Empty; byte[] inputBytes = secret; //SecureRandom random = new SecureRandom(); if (iv == null) { iv = new byte[16]; } //random.NextBytes(iv); iv_base64 = Convert.ToBase64String(iv); string keyStringBase64 = Convert.ToBase64String(key); //Set up AesEngine engine = new AesEngine(); CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine), new Pkcs7Padding()); KeyParameter keyParam = new KeyParameter(Convert.FromBase64String(keyStringBase64)); ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16); // Encrypt cipher.Init(true, keyParamWithIV); byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)]; int length = cipher.ProcessBytes(inputBytes, outputBytes, 0); cipher.DoFinal(outputBytes, length); //Do the final block return(outputBytes); }
public static string GenEncrypedPin(string pin, string pinToken, string sessionId, RsaPrivateCrtKeyParameters rsa, ulong it) { ulong time = (ulong)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; var bPinToken = Convert.FromBase64String(pinToken); IAsymmetricBlockCipher cipherRsa = new RsaBlindedEngine(); cipherRsa = new OaepEncoding(cipherRsa, new Sha256Digest(), new Sha256Digest(), Encoding.ASCII.GetBytes(sessionId)); BufferedAsymmetricBlockCipher cipher = new BufferedAsymmetricBlockCipher(cipherRsa); cipher.Init(false, rsa); cipher.ProcessBytes(bPinToken, 0, bPinToken.Length); var key = cipher.DoFinal(); var bPin = Encoding.ASCII.GetBytes(pin); var btime = BitConverter.GetBytes(time); var biterator = BitConverter.GetBytes(it); int len = bPin.Length + btime.Length + biterator.Length; IBlockCipher cipherAes = new AesEngine(); int bsize = cipherAes.GetBlockSize(); KeyParameter keyParameter = new KeyParameter(key); int nPadding = bsize - len % bsize; var bPadding = new byte[nPadding]; len += (len % bsize == 0 ? 0 : nPadding); var blocks = new byte[len]; Array.Copy(bPin, blocks, bPin.Length); Array.Copy(btime, 0, blocks, bPin.Length, btime.Length); Array.Copy(biterator, 0, blocks, bPin.Length + btime.Length, biterator.Length); Array.Copy(bPadding, 0, blocks, bPin.Length + btime.Length + biterator.Length, nPadding); var iv = new byte[bsize]; random.NextBytes(iv); CbcBlockCipher cbcBc = new CbcBlockCipher(cipherAes); ParametersWithIV parametersWithIV = new ParametersWithIV(keyParameter, iv); BufferedBlockCipher bc = new BufferedBlockCipher(cbcBc); bc.Init(true, parametersWithIV); var bOut = bc.ProcessBytes(blocks); var rz = new byte[bOut.Length + bsize]; Array.Copy(iv, rz, iv.Length); Array.Copy(bOut, 0, rz, iv.Length, bOut.Length); return(Convert.ToBase64String(rz)); }
/// <summary> /// Symmetrical decryption of the bytes /// </summary> /// <param name="key">Password for the encryption</param> /// <param name="bytes">Bytes array which should be decrypted</param> /// <returns></returns> public static byte[] DecryptBytes(byte[] key, byte[] secret, byte[] iv = null) { var Keysize = 256 / 8; int iterationCount = 1; if (iv == null) { iv = new byte[16]; } AesEngine engine = new AesEngine(); CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine), new Pkcs7Padding()); KeyParameter keyParam = new KeyParameter(key); ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16); byte[] outputBytes = secret; cipher.Init(false, keyParamWithIV); byte[] comparisonBytes = new byte[cipher.GetOutputSize(outputBytes.Length)]; int length = cipher.ProcessBytes(outputBytes, comparisonBytes, 0); cipher.DoFinal(comparisonBytes, length); //Do the final block byte[] output = comparisonBytes.Take(comparisonBytes.Length).ToArray(); return(output); }
/// <summary> /// Encapsulates the specified links into an RSDF container. /// </summary> /// <param name="links">The links.</param> /// <returns> /// Base-16-encoded RSDF container. /// </returns> public static string CreateRSDF(string[] links) { var aes = new AesEngine(); var cfb = new CfbBlockCipher(aes, 8); var pad = new BufferedBlockCipher(cfb); var sb = new StringBuilder(); pad.Init(true, new ParametersWithIV(new KeyParameter(RSDFKey), RSDFIV)); foreach (var link in links) { var input = Encoding.UTF8.GetBytes(link); var output = new byte[input.Length]; for (var i = 0; i < input.Length; i++) { output[i] = pad.ProcessByte(input[i])[0]; } sb.Append(Convert.ToBase64String(output)); sb.Append(Environment.NewLine); } return(BitConverter.ToString(Encoding.ASCII.GetBytes(sb.ToString())).Replace("-", string.Empty)); }
private AesEngine MakeMacCipher() { AesEngine aesFastEngine = new AesEngine(); aesFastEngine.Init(true, new KeyParameter(_macSecret)); return(aesFastEngine); }
public void TestKeyScrambler() { var Engine = new AesEngine(GetBoot9()); Engine.SelectKeyslot(0x11); Engine.SetMode(AesMode.ECB); byte[] knownKey = "EE2EA93B450FFCF4D562FF02040122C8".ToByteArray(); byte[] knownResult = "44D193F977EC6092388ABFE4D9C73A97".ToByteArray(); byte[] KeyX = new byte[0x10]; byte[] KeyY = new byte[0x10]; Engine.SetKeyX(KeyX); Engine.SetKeyY(KeyY); Engine.SetIV(new byte[0x10]); byte[] firstEncrypted = Engine.Encrypt(new byte[0x10]); KeyX[0xF] = 1; KeyY[0xF] = 4; Engine.SetKeyX(KeyX); Engine.SetKeyY(KeyY); byte[] secondEncrypted = Engine.Encrypt(new byte[0x10]); Engine.SetNormalKey(knownKey); byte[] knownEncrypted = Engine.Encrypt(new byte[0x10]); CollectionAssert.AreEqual(knownResult, knownEncrypted); CollectionAssert.AreEqual(knownResult, firstEncrypted); CollectionAssert.AreEqual(knownResult, secondEncrypted); }
/// <summary> /// Encapsulates the specified links into a CCF container. /// </summary> /// <param name="name">The name of the package.</param> /// <param name="links">The links.</param> /// <returns> /// CCF container. /// </returns> public static byte[] CreateCCF(string name, string[] links) { var sb = new StringBuilder(); sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); sb.Append("<CryptLoad>"); sb.Append("<Package service=\"\" name=\"" + name + "\" url=\"Directlinks\">"); foreach (var link in links) { sb.Append("<Download Url=\"" + link + "\">"); sb.Append("<Url>" + link + "</Url>"); //sb.Append("<FileName></FileName>"); //sb.Append("<FileSize></FileSize>"); sb.Append("</Download>"); } sb.Append("</Package>"); sb.Append("</CryptLoad>"); var aes = new AesEngine(); var cbc = new CbcBlockCipher(aes); var pk7 = new Pkcs7Padding(); var pad = new PaddedBufferedBlockCipher(cbc, pk7); pad.Init(true, new ParametersWithIV(new KeyParameter(CCFKey), CCFIV)); return(pad.DoFinal(Encoding.UTF8.GetBytes(sb.ToString()))); }
/// <summary> /// Borrowed from https://github.com/vadimkantorov/wemosetup/blob/master/wemosetup.py /// </summary> /// <param name="password"></param> /// <param name="metainfo"></param> /// <returns></returns> private string EncryptPassword(string password, string metainfo) { string[] metaInfoParts = metainfo.Split('|'); string keydata = metaInfoParts[0].Substring(0, 6) + metaInfoParts[1] + metaInfoParts[0].Substring(6, 6); string salt = keydata.Substring(0, 8); string iv = keydata.Substring(0, 16); byte[] passwordAsBytes = Encoding.ASCII.GetBytes(Password); OpenSslPbeParametersGenerator keyGen = new OpenSslPbeParametersGenerator(); keyGen.Init(Encoding.ASCII.GetBytes(keydata), Encoding.ASCII.GetBytes(salt)); ICipherParameters cipherParams = keyGen.GenerateDerivedParameters("AES128", 128); AesEngine engine = new AesEngine(); CbcBlockCipher blockCipher = new CbcBlockCipher(engine); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); ParametersWithIV keyParamWithIv = new ParametersWithIV(cipherParams, Encoding.ASCII.GetBytes(iv), 0, 16); cipher.Init(true, keyParamWithIv); byte[] outputBytes = new byte[cipher.GetOutputSize(passwordAsBytes.Length)]; int length = cipher.ProcessBytes(passwordAsBytes, outputBytes, 0); cipher.DoFinal(outputBytes, length); return(Convert.ToBase64String(outputBytes)); }
public AesResult Encrypt(string input, string keyString) { var inputBytes = Encoding.UTF8.GetBytes(input); var iv = new byte[16]; new SecureRandom().NextBytes(iv); //Set up var engine = new AesEngine(); var blockCipher = new CbcBlockCipher(engine); //CBC var cipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7 var keyParam = new KeyParameter(Convert.FromBase64String(keyString)); var keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16); // Encrypt cipher.Init(true, keyParamWithIV); var outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)]; var length = cipher.ProcessBytes(inputBytes, outputBytes, 0); cipher.DoFinal(outputBytes, length); //Do the final block var encryptedInput = Convert.ToBase64String(outputBytes); return(new AesResult { EncryptedText = encryptedInput, Iv = iv }); }
private static byte[] Scp03_kdf(byte[] key, byte constant, byte[] context, int blocklen_bits) { // 11 bytes byte[] label = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; //TODO: test, should order be reversed? byte[] bo = Arrays.ConcatenateAll( label, // 11 bytes of label new byte[] { constant }, // constant for the last byte new byte[] { 0x00 }, // separator new byte[] { (byte)((blocklen_bits >> 8) & 0xFF) }, // block size in two bytes new byte[] { (byte)(blocklen_bits & 0xFF) } ); byte[] blocka = bo; byte[] blockb = context; IBlockCipher cipher = new AesEngine(); CMac cmac = new CMac(cipher); KDFCounterBytesGenerator kdf = new KDFCounterBytesGenerator(cmac); kdf.Init(new KDFCounterParameters(key, blocka, blockb, 8)); // counter size in bits byte[] cgram = new byte[blocklen_bits / 8]; kdf.GenerateBytes(cgram, 0, cgram.Length); return(cgram); }
public static byte[] EncryptAES(byte[] inputBytes, byte[] key, byte[] iVector) { //Convert.FromBase64String(keyString); //Set up byte[] iv = iVector; //new byte[16]; AesEngine engine = new AesEngine(); CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7 KeyParameter keyParam = new KeyParameter(key); ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16); // Encrypt cipher.Init(true, keyParamWithIV); byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)]; int length = cipher.ProcessBytes(inputBytes, outputBytes, 0); cipher.DoFinal(outputBytes, length); //Do the final block //string encryptedInput = Convert.ToBase64String(outputBytes); //cipher.Init(false, keyParamWithIV); //byte[] comparisonBytes = new byte[cipher.GetOutputSize(outputBytes.Length)]; //length = cipher.ProcessBytes(outputBytes, comparisonBytes, 0); //cipher.DoFinal(comparisonBytes, length); //Do the final block return(outputBytes); }
public void TestAesCCM() { var Engine = new AesEngine(); Engine.SelectKeyslot(0x11); Engine.SetMode(AesMode.CCM); // Uses data from English pre-release "Example" ORAS QR code. Engine.SetNormalKey("044AC6D4576EEA180C12AE92E24FA369".ToByteArray()); Engine.SetNonce("D4EEB874289E6C13A4578621".ToByteArray()); byte[] mac = "EF0C908A30ADAEE74C0F8120B6703E2C".ToByteArray(); Engine.SetMAC(mac); byte[] encrypted = "5470E724C18E2D2D68B390E0D54E87EBB28E21B1C20552AA35FF6393436DCBAF0E680B6D37D2F0593E677D6229C3D186D3B561699B014A2F6CB4AB523035C317C6957A583E5031977F872D08677F530441B049C9D9A365776B63245DBC25EF35E79EB2FBA870A20F1A02CD13FCD8E7511EBF5D29C125BDDAB9AC4426A1FE2B39B23AF861A0D05E31A0505FBEDBFE78B6FBA0D92435D3A83C7CC5DBA50CC3E9A4556631CE5BC20F9D35AD4CC877C84176A84C160D7BB6C31C4EAB09C536D6BB8EB2D4B30A446D9578BB23EBB18B4FA7F44D1223340C5D3846D299609F9E6FEDBC0AD5527D6AB6D0426AAC8F576C2AF8B6C6CEB5090BACFE735A074DBFEB7B05FEBF585F8FBF6466F46BD3D55CC19755437A082400C88490F8E899B732E3E54E0FB4DD1C70CFC85FE959319767BCE2DF47E8903529935A62BDC052A46BC860BADAE212EBFACF36972946DEFE9D2B990896FB20EC2B7AD35408845E1D4F020CF2AD124B4E2539393E7488173A00C28584380E87B8447EF74F7A65DA4E81B383017F62F5A3845A302E0F3CD28A1F62141174E63C546E9A1CDFD156F5880599E306BCB65C71623E8585E2869A0E510899F2E4C8A68360D74EB056AE347B42F7BC8BC6B762C6933ADAD723D95DF5A5BD5A9EB88208E669AA19F3BBDFAAE860E963C4D48B8CE527DE02E9F2EE54388D4FC9C73AAFB44053CE84E88518C0CAD9D175B3AB15E4276385AC200AC448468982DEA1E881A22E5BCF5DEA52" .ToByteArray(); byte[] decrypted = "542E11C193DBB9232B164C6BFFFF0000000000003500000000004F0072006C0061006E0064006F0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005900610079000000000000000000000000000000000000000000000000000000000044006F00200079006F007500720020006200650073007400000000000000000000000000000000000000000000000000000000000000000000000000480065006C006C006F0021000000000000000000000000000000000000000000000043006F006E00670072006100740075006C006100740069006F006E0073002100000002000008FF00000000350015551FDA66FC0000009C010F0046005B000041011300000000000000000000000B0019131205460363D5554182FF0000003500F900940022010042010B0000000000000000000000110F1A1B0810460463F138AADA020100003A0039007F002301004302060000000000000000000000050F021B13034602631E1E1E1E1EAD1314151617FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF121314151617000000000000000000000000000000000000000C0C0C0C0C0C00000000000000000000000000000000000000010101010101000000000000000000000000000000000000000000000000000000000000000000000000" .ToByteArray(); byte[] decTest = Engine.Decrypt(encrypted); CollectionAssert.AreEqual(decrypted, decTest); // Clear MAC to verify the calculated actually matches Engine.SetMAC("00000000000000000000000000000000".ToByteArray()); byte[] encTest = Engine.Encrypt(decrypted); CollectionAssert.AreEqual(encrypted, encTest); CollectionAssert.AreEqual(mac, Engine.GetMAC()); }
protected override string EncryptOrDecrypt(bool type, string plainStr) { //Demo params string keyString = GetEncryptionKey(); string input = plainStr; byte[] inputBytes; byte[] iv = System.Text.Encoding.UTF8.GetBytes("0123456789012345"); byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(keyString); //Set up AesEngine engine = new AesEngine(); CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7 KeyParameter keyParam = new KeyParameter(keyBytes); ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, iv.Length); if (type) { // Encrypt input = EncodeNonAsciiCharacters(input); inputBytes = Encoding.UTF8.GetBytes(input); cipher.Init(true, keyParamWithIV); byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)]; int length = cipher.ProcessBytes(inputBytes, outputBytes, 0); cipher.DoFinal(outputBytes, length); //Do the final block string encryptedInput = Convert.ToBase64String(outputBytes); return(encryptedInput); } else { try { //Decrypt inputBytes = Convert.FromBase64CharArray(input.ToCharArray(), 0, input.Length); cipher.Init(false, keyParamWithIV); byte[] encryptedBytes = new byte[cipher.GetOutputSize(inputBytes.Length)]; int encryptLength = cipher.ProcessBytes(inputBytes, encryptedBytes, 0); int numOfOutputBytes = cipher.DoFinal(encryptedBytes, encryptLength); //Do the final block //string actualInput = Encoding.UTF8.GetString(encryptedBytes, 0, encryptedBytes.Length); int len = Array.IndexOf(encryptedBytes, (byte)0); len = (len == -1) ? encryptedBytes.Length : len; string actualInput = Encoding.UTF8.GetString(encryptedBytes, 0, len); return(actualInput); } catch (Exception ex) { #if (ENABLE_PUBNUB_LOGGING) pnLog.WriteToLog(string.Format("Decrypt Error. {0}", ex.ToString()), PNLoggingMethod.LevelVerbose); #endif throw ex; //LoggingMethod.WriteToLog(string.Format("DateTime {0} Decrypt Error. {1}", DateTime.Now.ToString(), ex.ToString()), LoggingMethod.LevelVerbose); //return "**DECRYPT ERROR**"; } } }
private static void TestRijndael() { // Test vector (official ECB test vector #356) byte[] pbIV = new byte[16]; byte[] pbTestKey = new byte[32]; byte[] pbTestData = new byte[16]; byte[] pbReferenceCT = new byte[16] { 0x75, 0xD1, 0x1B, 0x0E, 0x3A, 0x68, 0xC4, 0x22, 0x3D, 0x88, 0xDB, 0xF0, 0x17, 0x97, 0x7D, 0xD7 }; int i; for (i = 0; i < 16; ++i) { pbIV[i] = 0; } for (i = 0; i < 32; ++i) { pbTestKey[i] = 0; } for (i = 0; i < 16; ++i) { pbTestData[i] = 0; } pbTestData[0] = 0x04; #if KeePassUAP AesEngine r = new AesEngine(); r.Init(true, new KeyParameter(pbTestKey)); if (r.GetBlockSize() != pbTestData.Length) { throw new SecurityException(KLRes.EncAlgorithmAes + " (BS)."); } r.ProcessBlock(pbTestData, 0, pbTestData, 0); #else RijndaelManaged r = new RijndaelManaged(); if (r.BlockSize != 128) // AES block size { Debug.Assert(false); r.BlockSize = 128; } r.IV = pbIV; r.KeySize = 256; r.Key = pbTestKey; r.Mode = CipherMode.ECB; ICryptoTransform iCrypt = r.CreateEncryptor(); iCrypt.TransformBlock(pbTestData, 0, 16, pbTestData, 0); #endif if (!MemUtil.ArraysEqual(pbTestData, pbReferenceCT)) { throw new SecurityException(KLRes.EncAlgorithmAes + "."); } }
private static BufferedBlockCipher CreateAesEcbCipher(byte[] key) { AesEngine engine = new AesEngine(); KeyParameter parameter = new KeyParameter(key); BufferedBlockCipher cipher = new BufferedBlockCipher(engine); cipher.Init(false, parameter); return(cipher); }
public static void EncryptFile(string inFile, string outFile, string in_key) { byte[] key = Encoding.ASCII.GetBytes(in_key); byte[] IV = Encoding.ASCII.GetBytes(iv); AesEngine aesEngine = new AesEngine(); CbcBlockCipher cbc = new CbcBlockCipher(aesEngine); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbc); KeyParameter keySpec = new KeyParameter(key); ICipherParameters parameters = new ParametersWithIV(keySpec, IV); cipher.Init(true, parameters); using (FileStream fin = File.OpenRead(inFile), fout = File.Open(outFile, FileMode.Create)) { BinaryReader br = new BinaryReader(fin); BinaryWriter bw = new BinaryWriter(fout); int block = 0; //初始化缓冲区 byte[] decryptor_data = null; if (fin.Length > EnBufferLen) { decryptor_data = new byte[EnBufferLen]; } else { decryptor_data = new byte[fin.Length]; } while ((block = br.Read(decryptor_data, 0, decryptor_data.Length)) > 0) { if (decryptor_data.Length != block) { byte[] temp = new byte[block]; Buffer.BlockCopy(decryptor_data, 0, temp, 0, block); decryptor_data = temp; } // 开始处理编码 byte[] encrypted = new byte[cipher.GetOutputSize(decryptor_data.Length)]; int bytesProcessed1 = cipher.ProcessBytes(decryptor_data, 0, decryptor_data.Length, encrypted, 0); //保存进文件 int write_len = encrypted.Length; bw.Write(encrypted, 0, bytesProcessed1); } byte[] output = new byte[cipher.GetOutputSize(decryptor_data.Length)]; int bytesProcessed2 = cipher.DoFinal(output, 0); if (bytesProcessed2 > 0) { bw.Write(output, 0, bytesProcessed2); } br.Close(); bw.Close(); } }
/// <inheritdoc /> public DigestBuilder(CryptoConfig config) { _config = config; _myAes = new AesEngine(); if (_config.DigestKey == null) { GenerateKey(AesAlgo + AesKeySize); } }
protected bool InitializeAESKey() { _AesParameters = new KeyParameter(Hex.Decode(_KeyValue)); _AesEngine = new AesEngine(); _AesEngine.Init(true, _AesParameters); theKey = _AesParameters.GetKey(); return(false); }
public void TestBouncyCastleAes() { var aesEngine = new AesEngine(); //var parametersWithIv = new ParametersWithIV(new KeyParameter(pbTestKey), pbIV); aesEngine.Init(true, new KeyParameter(_pbTestKey)); Assert.Equal(aesEngine.GetBlockSize(), _pbTestData.Length); aesEngine.ProcessBlock(_pbTestData, 0, _pbTestData, 0); Assert.True(MemUtil.ArraysEqual(_pbTestData, _pbReferenceCt)); }
/// <summary> /// Create a buffered cipher to encrypt or decrypt a stream as it is being read /// </summary> /// <param name="forEncryption">forEncryption if true the cipher is initialised for encryption, if false for decryption</param> /// <param name="key">Key to be used for encryption</param> /// <param name="nonce">Nonce to be used for encryption</param> /// <param name="tagSize">Tag size in bits for the tag appended in the end of the stream</param> /// <param name="associatedText">Additional associated data</param> /// <returns></returns> internal static IBufferedCipher CreateCipher(bool forEncryption, byte[] key, int tagSize, byte[] nonce, byte[] associatedText) { var aesEngine = new AesEngine(); var blockCipher = new GcmBlockCipher(aesEngine); var aeadBlockCipher = new BufferedAeadBlockCipher(blockCipher); var parameters = new AeadParameters(new KeyParameter(key), tagSize, nonce, associatedText); aeadBlockCipher.Init(forEncryption, parameters); return(aeadBlockCipher); }
public static bool TransformKeyManaged(byte[] pbNewKey32, byte[] pbKeySeed32, ulong uNumRounds) { #if KeePassRT KeyParameter kp = new KeyParameter(pbKeySeed32); AesEngine aes = new AesEngine(); aes.Init(true, kp); for (ulong i = 0; i < uNumRounds; ++i) { aes.ProcessBlock(pbNewKey32, 0, pbNewKey32, 0); aes.ProcessBlock(pbNewKey32, 16, pbNewKey32, 16); } #else #if KeePass2PCL var aes = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesEcb); var key = aes.CreateSymmetricKey(pbKeySeed32); var iCrypt = WinRTCrypto.CryptographicEngine.CreateEncryptor(key); #else byte[] pbIV = new byte[16]; Array.Clear(pbIV, 0, pbIV.Length); RijndaelManaged r = new RijndaelManaged(); if (r.BlockSize != 128) // AES block size { Debug.Assert(false); r.BlockSize = 128; } r.IV = pbIV; r.Mode = CipherMode.ECB; r.KeySize = 256; r.Key = pbKeySeed32; ICryptoTransform iCrypt = r.CreateEncryptor(); #endif // !iCrypt.CanReuseTransform -- doesn't work with Mono if ((iCrypt == null) || (iCrypt.InputBlockSize != 16) || (iCrypt.OutputBlockSize != 16)) { Debug.Assert(false, "Invalid ICryptoTransform."); Debug.Assert((iCrypt.InputBlockSize == 16), "Invalid input block size!"); Debug.Assert((iCrypt.OutputBlockSize == 16), "Invalid output block size!"); return(false); } for (ulong i = 0; i < uNumRounds; ++i) { iCrypt.TransformBlock(pbNewKey32, 0, 16, pbNewKey32, 0); iCrypt.TransformBlock(pbNewKey32, 16, 16, pbNewKey32, 16); } #endif return(true); }
public override string EncryptPayload(string appSkey) { //return null; AesEngine aesEngine = new AesEngine(); aesEngine.Init(true, new KeyParameter(StringToByteArray(appSkey))); byte[] rfu = new byte[1]; rfu[0] = 0x0; //downlink direction byte direction = 0x01; byte[] aBlock = { 0x01, 0x00, 0x00, 0x00, 0x00, direction, (byte)(devAddr[3]), (byte)(devAddr[2]), (byte)(devAddr[1]), (byte)(devAddr[0]), (byte)(fcnt[0]), (byte)(fcnt[1]), 0x00, 0x00, 0x00, 0x00 }; byte[] frmpayload; if (cfList != null) { frmpayload = appNonce.Concat(netID).Concat(devAddr).Concat(rfu).Concat(rxDelay).Concat(cfList).Concat(mic).ToArray(); } else { frmpayload = appNonce.Concat(netID).Concat(devAddr).Concat(rfu).Concat(rxDelay).Concat(mic).ToArray(); } byte[] sBlock = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; int size = 12 + (cfList != null ? cfList.Length : 0); byte[] decrypted = new byte[size]; byte bufferIndex = 0; short ctr = 1; int i; while (size >= 16) { aBlock[15] = (byte)((ctr) & 0xFF); ctr++; aesEngine.ProcessBlock(aBlock, 0, sBlock, 0); for (i = 0; i < 16; i++) { decrypted[bufferIndex + i] = (byte)(frmpayload[bufferIndex + i] ^ sBlock[i]); } size -= 16; bufferIndex += 16; } if (size > 0) { aBlock[15] = (byte)((ctr) & 0xFF); aesEngine.ProcessBlock(aBlock, 0, sBlock, 0); for (i = 0; i < size; i++) { decrypted[bufferIndex + i] = (byte)(frmpayload[bufferIndex + i] ^ sBlock[i]); } } rawMessage = decrypted; return(Encoding.Default.GetString(decrypted)); }
// Coder init public AEScoder(KeyParameter Aeskey) { // Works in EBC/PKCS7 only! // setup AES cipher in ECB mode with PKCS7 padding AesEngine engine = new AesEngine(); _wkCipher = new PaddedBufferedBlockCipher(engine, new Pkcs7Padding()); //Default scheme is PKCS7 // _wkCipher = (BufferedBlockCipher) CipherUtilities.GetCipher("AES/ECB/PKCS7Padding"); this.key = Aeskey; _wkCipher.Reset(); }
protected byte[] AES_CMAC(CBORObject alg, byte[] K) { int cbitKey; int cbitTag; IBlockCipher aes = new AesEngine(); CMac mac = new CMac(aes); KeyParameter ContentKey; // The requirements from spec // IV is 128 bits of zeros // key sizes are 128, 192 and 256 bits // Authentication tag sizes are 64 and 128 bits Debug.Assert(alg.Type == CBORType.TextString); switch (alg.AsString()) { case "AES-CMAC-128/64": cbitKey = 128; cbitTag = 64; break; case "AES-CMAC-256/64": cbitKey = 256; cbitTag = 64; break; default: throw new CoseException("Unrecognized algorithm"); } if (K.Length != cbitKey / 8) { throw new CoseException("Key is incorrectly sized"); } ContentKey = new KeyParameter(K); // Build the text to be digested mac.Init(ContentKey); byte[] toDigest = BuildContentBytes(); byte[] C = new byte[128 / 8]; mac.BlockUpdate(toDigest, 0, toDigest.Length); mac.DoFinal(C, 0); byte[] rgbOut = new byte[cbitTag / 8]; Array.Copy(C, 0, rgbOut, 0, cbitTag / 8); return(rgbOut); }
public static byte[] DecryptAesCtr(Stream inputStream, byte[] key, byte[] iv) { AesEngine engine = new AesEngine(); KeyParameter keyParameter = new KeyParameter(key); ICipherParameters parameters = new ParametersWithIV(keyParameter, iv); BufferedBlockCipher cipher = new BufferedBlockCipher(new SicBlockCipher(engine)); cipher.Init(false, parameters); return(DecryptAes(inputStream, cipher, inputStream.Length)); }
/// <summary> /// Creates a new instance of AESCipher /// </summary> public AesCipher(bool forEncryption, byte[] key, byte[] iv) { IBlockCipher aes = new AesEngine(); IBlockCipher cbc = new CbcBlockCipher(aes); _bp = new PaddedBufferedBlockCipher(cbc); KeyParameter kp = new KeyParameter(key); ParametersWithIV piv = new ParametersWithIV(kp, iv); _bp.Init(forEncryption, piv); }
private static void InitializeEncryption() { if (cipher == null || keyParamWithIV == null) { AesEngine engine = new AesEngine(); CbcBlockCipher blockCipher = new CbcBlockCipher(engine); cipher = new PaddedBufferedBlockCipher(blockCipher); KeyParameter keyParam = new KeyParameter(GenerateArray(32)); keyParamWithIV = new ParametersWithIV(keyParam, GenerateArray(16), 0, 16); } }
private static byte[] Scp03_mac(byte[] keybytes, byte[] msg, int lengthBits) { // FIXME: programmatically set the crypto backend IBlockCipher cipher = new AesEngine(); CMac cmac = new CMac(cipher); cmac.Init(new KeyParameter(keybytes)); cmac.BlockUpdate(msg, 0, msg.Length); byte[] outVal = new byte[cmac.GetMacSize()]; cmac.DoFinal(outVal, 0); return(Arrays.CopyOf(outVal, lengthBits / 8)); }
private static void init(byte[] bytesSessionkey) { byte[] iv = new byte[128]; AesEngine engine = new AesEngine(); OfbBlockCipher blockCipher = new OfbBlockCipher(engine, bufsize); //OFB mcipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7 KeyParameter keyParam = new KeyParameter(bytesSessionkey); mkeyParamWithIV = new ParametersWithIV(keyParam, iv, 0, bufsize); }
private ICryptoEngine GenerateEngine() { var engine = new AesEngine(txtKey.Text); if (cbxUseKeySize.Checked) { var keySize = EnumerationConversions.GetEnumName<AesKeySize>(cmbKeySize.SelectedItem.ToString()); engine.SetKeySize(keySize); } if (cbxUseInitVector.Checked) { engine.SetInitVector(txtInitVector.Text); } if (cbxUseKeySalt.Checked) { engine.SetSalt(txtSalt.Text); } if (cbxUseRandomSalt.Checked) { engine.SetRandomSaltLength((int)nudSaltMin.Value, (int)nudSaltMax.Value); } if (cbxUsePasswordIterations.Checked) { engine.SetIterations((int)nudIterations.Value); } if (cbxUseEncoding.Checked) { engine.SetEncoding(cmbEncoding.SelectedItem as Encoding); } if (cbxUseHashAlgorithm.Checked) { engine.SetHashAlgorithm((HashType)cmbHashAlgorithm.SelectedItem); } return engine; }