//---------------------------------------------------------------------------------------------- //Фильтрация по максимальному значению спектра public Complex[] FilterByMaxSpectrumValue(Complex[] fourierTransformValues) { double[] spectrumValues = this.GetFourierTransformSpectrum(fourierTransformValues); int maxValueIndex1 = ArrayOperator.GetMaxValueIndex(spectrumValues); spectrumValues[maxValueIndex1] = 0; int maxValueIndex2 = ArrayOperator.GetMaxValueIndex(spectrumValues); spectrumValues[maxValueIndex2] = 0; int maxValueIndex3 = ArrayOperator.GetMaxValueIndex(spectrumValues); spectrumValues[maxValueIndex3] = 0; Complex[] resultValues = new Complex[fourierTransformValues.Length]; for (int index = 0; index < fourierTransformValues.Length; index++) { resultValues[index] = new Complex(0, 0); } resultValues[maxValueIndex1] = fourierTransformValues[maxValueIndex1]; resultValues[maxValueIndex2] = fourierTransformValues[maxValueIndex2]; resultValues[maxValueIndex3] = fourierTransformValues[maxValueIndex3]; return(resultValues); }
public void ExtactColFromMatrixMethodReturnsSpecificSymbolInsteadOfNullOnSpecificPosition() { var arrOperator = new ArrayOperator(); var randomGen = new RandomGenerator(); var fakeAlphabet = new string[] { null, null, null, null, null, null, "a" }; var fakeMatrix = new string[5, 5]; fakeMatrix[0, 0] = "a"; fakeMatrix[1, 0] = "b"; fakeMatrix[2, 0] = null; fakeMatrix[3, 0] = null; fakeMatrix[4, 0] = "a"; var counter = 0; var stringToCompare = arrOperator.ExtractColFromMatrix(fakeMatrix, 0); for (int i = 0; i < stringToCompare.Length; i++) { if (stringToCompare[i].ToString() == GlobalConstants.SpecificSymbolToReplaceNull) { counter++; } } Assert.AreEqual(2, counter); }
/// <summary>復号化</summary> /// <param name="input">AeadResult</param> /// <returns>平文(plaintext)</returns> public override byte[] Decrypt(AeadResult input) { // 初期化 this.InitAesCbc(false); //認証タグ(MAC)を取得 // Concatenate the [AAD], the [Initialization Vector], the [ciphertext], and the [AL value]. byte[] temp = ArrayOperator.CombineArray(this.AAD, this.IV); temp = ArrayOperator.CombineArray(temp, input.Ciphert); temp = ArrayOperator.CombineArray(temp, this.AL); byte[] tag = this._hmac.ComputeHash(temp); Array.Resize(ref tag, TAG_LEN); // タグの確認 if (!tag.SequenceEqual(input.Tag)) { return(null); } // CCM操作の実行 byte[] plaint = new byte[this._aesCBC.GetOutputSize(input.Ciphert.Length)]; int len = this._aesCBC.ProcessBytes(input.Ciphert, 0, input.Ciphert.Length, plaint, 0); len += this._aesCBC.DoFinal(plaint, len); Array.Resize(ref plaint, len); // 平文を返す。 return(plaint); }
public void ExtactColFromMatrixMethodReturnsSpecificSymbolInsteadOfNull() { var arrOperator = new ArrayOperator(); var randomGen = new RandomGenerator(); var fakeAlphabet = new string[] { null, null, null, null, null, null, "a" }; var fakeMatrix = new string[10, 7]; for (int i = 0; i < fakeMatrix.GetLength(0); i++) { for (int col = 0; col < fakeMatrix.GetLength(1); col++) { fakeMatrix[i, col] = randomGen.GenerateRandomLetter(fakeAlphabet); } } var stringToCompare = arrOperator.ExtractColFromMatrix(fakeMatrix, 3); StringAssert.Contains(stringToCompare, GlobalConstants.SpecificSymbolToReplaceNull); }
//------------------------------------------------------------------------------------- //Скалярное произведение public static int operator *(IntegerVector operandOne, IntegerVector operandTwo) { int scalarProduct = ArrayOperator.ScalarProduct (operandOne.dataArray, operandTwo.dataArray); return(scalarProduct); }
/// <summary>BouncyCastleでMacのハッシュ値を計算して返す。</summary> /// <param name="data">データ(バイト配列)</param> /// <param name="key">キー(バイト配列)</param> /// <param name="mac">IMac</param> /// <returns>ハッシュ値(バイト配列)</returns> public static byte[] GetMacBytesByBC(byte[] data, byte[] key, IMac mac) { mac.Init(new KeyParameter(key)); mac.BlockUpdate(data, 0, data.Length); byte[] rtnVal = new byte[mac.GetMacSize()]; mac.DoFinal(rtnVal, 0); if (mac.AlgorithmName == "DESede/CBC" && 8 < rtnVal.Length) { rtnVal = ArrayOperator.CopyArray <byte>(rtnVal, 8); } return(rtnVal); // <HMAC> // mac = new HMac(new RipeMD160Digest()); // <MACTripleDES> // mac = new CbcBlockCipherMac(new DesEdeEngine(), 64)); // https://www.go4expert.com/articles/bouncy-castle-net-implementation-triple-t24829/ // ECBモードのDESEDEと、CBCモードのTriple DESがある。 // https://stackoverflow.com/questions/34660907/how-to-encrypt-decrypt-string-using-mactripledes // MACTripleDESはCBC-MACを使用します。 CBC-MACは、メッセージにゼロを埋め込んだ後にCBCモードを使用します。 }
//--------------------------------------------------------------------------------------------------------------------- public RealMatrix[] GetCorrectedInterferograms(RealMatrix[] interferograms, double[] gammaValues) { int width = interferograms[0].ColumnCount; int height = interferograms[0].RowCount; RealMatrix[] gammaCorrectedInterferograms = new RealMatrix[interferograms.Length]; for (int index = 0; index < gammaCorrectedInterferograms.Length; index++) { gammaCorrectedInterferograms[index] = new RealMatrix(height, width); } for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { double[] intensities = MatricesManager.GeValuesFromMatrices(y, x, interferograms); int cyclingShiftsCount = 0; double[] intensitiesByCyclingShift = ArrayOperator.GetArrayByCyclingShiftWithMinimumValueInOrigin(intensities, out cyclingShiftsCount); int optimalGammaValueIndex = this.GetOptimalGammaValueIndex(intensitiesByCyclingShift, gammaValues); double gamma = gammaValues[optimalGammaValueIndex]; double[] gammaCorrectedIntensities = ArrayOperator.GetValuesInPower(intensities, gamma); double[] resultValues = ArrayOperator.GetArrayByReverseCyclingShift(gammaCorrectedIntensities, cyclingShiftsCount); MatricesManager.SetValuesInMatrices(gammaCorrectedInterferograms, resultValues, y, x); } } return(gammaCorrectedInterferograms); }
public ActionResult <string> DeletePart(int position, int[] productIds) { try { if (productIds != null && productIds.Count() > 0) { if (position > 0 && position - 1 < productIds.Count()) { ArrayOperator arrayOperator = new ArrayOperator(); return(Content($"[{string.Join(",", arrayOperator.RemoveElementAt(position, productIds))}]")); } else { return(Content($"[{string.Join(",", productIds)}]")); } } else { return(Content(string.Empty)); } } catch (Exception ex) { return(BadRequest("Sorry!An error occurred while deleting the productId!\nError: " + ex.Message)); } }
//-------------------------------------------------------------------------------------- //Вектор синусов значений private RealVector GetSinVector(double[] values) { double[] sinValues = ArrayOperator.ComputeFunction(values, Math.Sin); RealVector sinVector = new RealVector(sinValues); return(sinVector); }
//-------------------------------------------------------------------------------------- //Вектор косинусов значений private RealVector GetCosVector(double[] values) { double[] cosValues = ArrayOperator.ComputeFunction(values, Math.Cos); RealVector cosVector = new RealVector(cosValues); return(cosVector); }
//---------------------------------------------------------------------------------------------------------- //Индексы интервалов с наибольшими значениями частот public int[] GetMaxFrequencyIntervalsIndecies(int count) { int[] intervalsIndecies = new int[count]; Dictionary <int, double> frequenciesDictionary = ArrayOperator.GetDictionary(this.frequencyValues); int index = 0; while (index < count) { double maxFrequencyValue = 0; int maxFrequencyIndex = 0; foreach (KeyValuePair <int, double> keyValuePair in frequenciesDictionary) { double value = keyValuePair.Value; int frequencyIndex = keyValuePair.Key; if (maxFrequencyValue < value) { maxFrequencyValue = value; maxFrequencyIndex = frequencyIndex; } } intervalsIndecies[index] = maxFrequencyIndex; frequenciesDictionary.Remove(maxFrequencyIndex); index++; } return(intervalsIndecies); }
//--------------------------------------------------------------------------------------------------------------------- //Индекс оптимального значения гаммы private int GetOptimalGammaValueIndex(double[] intensitiesByCyclingShift, double[] gammaValues) { Dictionary <int, double> rootMeanSquareErrors = new Dictionary <int, double>(); for (int index = 0; index < gammaValues.Length; index++) { double gamma = gammaValues[index]; double[] correctedIntensities = ArrayOperator.GetValuesInPower(intensitiesByCyclingShift, gamma); double rootMeanSquareError = Statistician.GetRootMeanSquareError(intensitiesByCyclingShift, correctedIntensities); rootMeanSquareErrors.Add(index, rootMeanSquareError); } int optimalIndex = 0; double optimalError = rootMeanSquareErrors[0]; foreach (KeyValuePair <int, double> pair in rootMeanSquareErrors) { if (pair.Value < optimalError) { optimalIndex = pair.Key; } } return(optimalIndex); }
//------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ //Умножение матриц public static IntegerMatrix operator *(IntegerMatrix matrixOne, IntegerMatrix matrixTwo) { int rowCountMatrixOne = matrixOne.rowCount; int rowCountMatrixTwo = matrixTwo.rowCount; int columnCountMatrixOne = matrixOne.columnCount; int columnCountMatrixTwo = matrixTwo.columnCount; if (columnCountMatrixOne != rowCountMatrixTwo) { throw new MatrixException(); } IntegerMatrix resultMatrix = new IntegerMatrix(rowCountMatrixOne, columnCountMatrixTwo); for (int row = 0; row < rowCountMatrixOne; row++) { int[] dataRow = matrixOne.GetRow(row); for (int column = 0; column < columnCountMatrixTwo; column++) { int[] dataColumn = matrixTwo.GetColumn(column); int result = ArrayOperator.ScalarProduct(dataRow, dataColumn); resultMatrix[row, column] = result; } } return(resultMatrix); }
//--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- //Вычисление матрицы фаз private RealMatrix CalculatePhaseMatrixByCirclePoints( Point3D[] circlePoints, Point[] imagePoints, int sizeX, int sizeY ) { bool sizeEuqality = ArrayOperator.IsArraySizesEqual(circlePoints, imagePoints); if (!sizeEuqality) { throw new Exception(); } ThreePointInterferogramDecoder decoder = new ThreePointInterferogramDecoder(); double[] phaseShifts = this.GetPhaseShifts(); RealMatrix phaseMatrix = new RealMatrix(sizeY, sizeX, this.DefaultPhaseValue); for (int index = 0; index < circlePoints.Length; index++) { Point3D point = circlePoints[index]; Point imagePoint = imagePoints[index]; double[] intensities = new double[] { point.X, point.Y, point.Z }; double phase = decoder.Decode(intensities, phaseShifts); //double phase = 2 * Math.PI - decoder.Decode( intensities, phaseShifts ); phaseMatrix[imagePoint.Y, imagePoint.X] = phase; } return(phaseMatrix); }
/// <summary>暗号化</summary> /// <param name="plaint">平文(plaintext)</param> /// <returns>AEAD実行結果オブジェクト</returns> public override void Encrypt(byte[] plaint) { // 初期化 this.InitAesCbc(true); // CCM操作の実行 byte[] ciphert = new byte[this._aesCBC.GetOutputSize(plaint.Length)]; int len = this._aesCBC.ProcessBytes(plaint, 0, plaint.Length, ciphert, 0); len += this._aesCBC.DoFinal(ciphert, len); // 認証タグ(MAC)を取得 // Concatenate the [AAD], the [IV], the [ciphertext], and the [AL value]. byte[] temp = ArrayOperator.CombineArray(this.AAD, this.IV); temp = ArrayOperator.CombineArray(temp, ciphert); temp = ArrayOperator.CombineArray(temp, this.AL); byte[] tag = this._hmac.ComputeHash(temp); Array.Resize(ref tag, TAG_LEN); // 結果を返す this._result = new AeadResult() { Aead = ArrayOperator.CombineArray(ciphert, tag), Ciphert = ciphert, Tag = tag, }; }
//------------------------------------------------------------------------------------- //Скалярное произведение public static double operator *(RealVector operandOne, RealVector operandTwo) { double scalarProduct = ArrayOperator.ScalarProduct (operandOne.dataArray, operandTwo.dataArray); return(scalarProduct); }
/// <summary>コンストラクタ</summary> public CheckCharCode(string startChar, string endChar, Encoding stringEncoding) { this.StartChar = startChar; this.EndChar = endChar; this.StringEncoding = stringEncoding; // 1文字のバイトデータを数値データ(long)に変換 this.StartCode = ArrayOperator.GetLongFromByte(stringEncoding.GetBytes(startChar)); this.EndCode = ArrayOperator.GetLongFromByte(stringEncoding.GetBytes(endChar)); }
//--------------------------------------------------------------------------------------------- //Случайные фазовые сдвиги private double[] GetRandomPhaseShifts(int count) { double[] phaseShifts = ArrayCreator.CreateRandomArray(count); ComputationalFunction function = new ComputationalFunction(delegate(double x) { return(x * 2 * Math.PI); }); phaseShifts = ArrayOperator.ComputeFunction(phaseShifts, function); phaseShifts = new double[] { 0, 2 * Math.PI / 3, 4 * Math.PI / 3 }; return(phaseShifts); }
public CrosswordGenerator(string[,] crossword, WordsOperator wordsOperator) { this.crossword = crossword; this.wordsOperator = wordsOperator; this.listOfAllWords = wordsOperator.ListOfAllWords; this.randomGenerator = new RandomGenerator(); this.arrayOperator = new ArrayOperator(); this.wordVerificator = new WordsVerificator(); this.painter = new Painter(); this.matrixWriter = new MatrixWriter(wordsOperator); this.crosswordSolver = new CrosswordSolver(); }
/// <summary> /// at_hash, c_hash, s_hashを作成 /// (SHA256→HS256,RS256,ES256対応可能) /// </summary> /// <param name="input">string</param> /// <returns>hash</returns> public static string CreateHash(string input) { // ID Token の JOSE Header にある // alg Header Parameterのアルゴリズムで使用されるハッシュアルゴリズムを用い、 // input(access_token や code) のASCII オクテット列からハッシュ値を求め、 byte[] bytes = GetHash.GetHashBytes( CustomEncode.StringToByte(input, CustomEncode.us_ascii), EnumHashAlgorithm.SHA256_M); // 左半分を base64url エンコードした値。 return(CustomEncode.ToBase64UrlString( ArrayOperator.ShortenByteArray(bytes, (bytes.Length / 2)))); }
/// <summary>バイト配列のハッシュ値を計算して返す。</summary> /// <param name="data">データ(バイト配列)</param> /// <param name="ekha">ハッシュ(キー付き)アルゴリズム列挙型</param> /// <param name="key">キー(バイト配列)</param> /// <returns>ハッシュ値(バイト配列)</returns> public static byte[] GetKeyedHashBytes(byte[] data, EnumKeyedHashAlgorithm ekha, byte[] key) { // HMACMD5 :どのサイズのキーでも受け入れる ◯ // HMACRIPEMD160:どのサイズのキーでも受け入れる ◯ // HMACSHA1 :どのサイズのキーでも受け入れる ◯ // HMACSHA256 :どのサイズのキーでも受け入れる ◯ // HMACSHA384 :どのサイズのキーでも受け入れる ◯ // HMACSHA512 :どのサイズのキーでも受け入れる ◯ // MACTripleDES :長さが 16 または 24 バイトのキーを受け入れる if (ekha == EnumKeyedHashAlgorithm.MACTripleDES) { if (24 <= key.Length) { key = ArrayOperator.ShortenByteArray(key, 24); } else if (16 <= key.Length) { key = ArrayOperator.ShortenByteArray(key, 16); } else { throw new ArgumentException( PublicExceptionMessage.ARGUMENT_INCORRECT, "byte[] key"); } } #if NETSTD // NETSTDの場合の実装 if (ekha == EnumKeyedHashAlgorithm.HMACRIPEMD160) { return(GetKeyedHash.GetMacBytesByBC( data, key, new HMac(new RipeMD160Digest()))); } else if (ekha == EnumKeyedHashAlgorithm.MACTripleDES) { return(GetKeyedHash.GetMacBytesByBC( data, key, new CbcBlockCipherMac(new DesEdeEngine(), 64))); } #endif // ハッシュ(キー付き)サービスプロバイダを生成 KeyedHashAlgorithm kha = HashAlgorithmCmnFunc. CreateKeyedHashAlgorithmSP(ekha, key); // ハッシュ(キー付き)を生成して返す。 byte[] temp = kha.ComputeHash(data); kha.Clear(); // devps(1725) return(temp); }
/// <summary> /// 文字コード範囲チェック /// </summary> /// <param name="ch"> /// チェックする文字(1文字) /// </param> /// <returns> /// true:範囲内 /// false:範囲外 /// </returns> public bool IsInRange(string ch) { // 1文字のバイトデータを数値データ(long)に変換 long charCode = ArrayOperator.GetLongFromByte(StringEncoding.GetBytes(ch)); // 範囲チェック if (charCode >= this.StartCode && charCode <= this.EndCode) { return(true); } else { return(false); } }
//------------------------------------------------------------------------------------------ //Умножение на вектор public static IntegerVector operator *(IntegerMatrix matrix, IntegerVector vector) { int columnCountMatrix = matrix.columnCount; int sizeVector = vector.Size; if (columnCountMatrix != sizeVector) { throw new MatrixException(); } IntegerVector newVector = new IntegerVector(sizeVector); int rowCountMatrix = matrix.rowCount; int[] dataVector = vector.GetDataArray(); for (int row = 0; row < rowCountMatrix; row++) { int[] dataRow = matrix.GetRow(row); int value = ArrayOperator.ScalarProduct(dataRow, dataVector); newVector[row] = value; } return(newVector); }
/// <summary>初期化(プロバイダ)</summary> /// <param name="forEncrypt">bool</param> private void InitAesCbc(bool forEncrypt) { // PaddedBufferedBlockCipher this._aesCBC = new PaddedBufferedBlockCipher( new CbcBlockCipher(new AesEngine()), new Pkcs7Padding()); // Initialization Vector. // IV must be the same length as block size this.IV = ArrayOperator.CopyArray <byte>(this.IV, this._aesCBC.GetBlockSize()); // 初期化 // EncKey length is 128 / 192 / 256 bits. this._aesCBC.Reset(); this._aesCBC.Init(forEncrypt, new ParametersWithIV( new KeyParameter(this.EncKey, 0, this.EncKey.Length), this.IV)); // MacKey this._hmac.Initialize(); this._hmac.Key = this.MacKey; }
//--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- //Вычисление матрицы фаз private RealMatrix CalculatePhaseMatrix( Point2D[] points, Point[] imagePoints, int sizeX, int sizeY ) { bool sizeEuqality = ArrayOperator.IsArraySizesEqual(points, imagePoints); if (!sizeEuqality) { throw new Exception(); } RealMatrix phaseMatrix = new RealMatrix(sizeY, sizeX, this.DefaultPhaseValue); for (int index = 0; index < points.Length; index++) { Point2D point = points[index]; Point imagePoint = imagePoints[index]; double phase = this.CalculatePhase(point.X, point.Y); phaseMatrix[imagePoint.Y, imagePoint.X] = phase; } return(phaseMatrix); }
public ActionResult <string> Reverse(int[] productIds) { try { if (productIds != null && productIds.Count() > 0) { ArrayOperator arrayOperator = new ArrayOperator(); //Reversing the array arrayOperator.Reverse(productIds); //Returns the reversed array return(Content($"[{string.Join(",", productIds)}]")); } else { return(Content(string.Empty)); } } catch (Exception ex) { return(BadRequest("Sorry! An error occurred while reversing the product!\nError:" + ex.Message)); } }
/// <summary>constructor</summary> /// <param name="cek">コンテンツ暗号化キー(CEK)</param> /// <param name="iv">初期化ベクトル</param> /// <param name="aad">追加認証データ(AAD)</param> public AeadAesGcm(byte[] cek, byte[] iv, byte[] aad) : base(cek, iv, aad) { // 各種サイズの初期化 this.InitSize(); if (cek.Length < CEK_LEN) { throw new ArgumentException("Length is less than 128 bits.", "cek"); } else if (cek.Length == CEK_LEN) { this.Cek = cek; } else { this.Cek = ArrayOperator.CopyArray(cek, CEK_LEN); } // Use of an IV of size 96 bits is REQUIRED with this algorithm. this._iv = iv; // The requested size of the Authentication Tag output MUST be 128 bits, regardless of the key size. this._aad = aad; }
//--------------------------------------------------------------------------------------- //Аппроксимировать public EllipseDescriptor Approximate(Point2D[] points) { RealMatrix matrixD = this.CreateMatrixD(points); RealMatrix transposedMatrixD = matrixD.GetTransposedMatrix(); RealMatrix matrixS = transposedMatrixD * matrixD; double[] eigenValues = this.CalculateEigenValues(matrixS); double[] absoluteEigenValues = ArrayOperator.GetAbsoluteValues(eigenValues); int minAbsoluteEigenValueIndex = ArrayOperator.GetMinValueIndex(absoluteEigenValues); double lambda = eigenValues[minAbsoluteEigenValueIndex]; RealMatrix matrixA = this.CreateMatrixA(matrixS, lambda); double[ , ] dataArrayMatrixA = matrixA.GetDataArray(); double[] dataArrayVectorB = new double[] { 1, 0, 0, 0, 0, 0 }; double[] values = this.SolveLinearSystem(dataArrayMatrixA, dataArrayVectorB); EllipseDescriptor ellipse = this.CreateEllipseDescriptor(values); return(ellipse); }
/// <summary>constructor</summary> /// <param name="cek">コンテンツ暗号化キー(CEK)</param> /// <param name="iv">初期化ベクトル</param> /// <param name="aad">追加認証データ(AAD)</param> public AeadAesCbc(byte[] cek, byte[] iv, byte[] aad) : base(cek, iv, aad) { // 各種サイズの初期化 this.InitSize(); // CEK -> MacKey & EncKey if (cek.Length < CEK_LEN) { throw new ArgumentException(string.Format("Length is less than {0} bytes.", this.CEK_LEN), "cek"); } this.MacKey = ArrayOperator.CopyArray <byte>(cek, MAC_KEY_LEN); this.EncKey = ArrayOperator.CopyArray <byte>(cek, ENC_KEY_LEN, ENC_KEY_LEN, 0); // Initialization Vector. this.IV = iv; // Additional Authenticated Data this.AAD = aad; // HMac this.AL = this.InitAL(); }
/// <summary>暗号化</summary> /// <param name="plaint">平文(plaintext)</param> /// <returns>AEAD実行結果オブジェクト</returns> public override void Encrypt(byte[] plaint) { // AesGcm実装を初期化 this.InitAesGcm(true); // GCM操作の実行 byte[] aead = new byte[this._aesGcm.GetOutputSize(plaint.Length)]; int len = this._aesGcm.ProcessBytes(plaint, 0, plaint.Length, aead, 0); len += this._aesGcm.DoFinal(aead, len); // GetMacで認証タグ(MAC)を取得 byte[] tag = this._aesGcm.GetMac(); // 結果を返す this._result = new AeadResult() { Aead = aead, // aead = ciphert + tag // <ciphertの抽出> // plaint.Lengthと、ciphert.Length - tag.Length を使う方法がある。 Ciphert = ArrayOperator.CopyArray <byte>(aead, plaint.Length), Tag = tag, }; }