FromBase64String() private method

private FromBase64String ( String s ) : byte[]
s String
return byte[]
Ejemplo n.º 1
0
        public static string Decrypt(byte[] cipherText, byte[] IV)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }

            // Declare the string used to hold the decrypted text.
            string plaintext = null;

            // Create an Aes object with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Convert.FromBase64String(_key);
                aesAlg.IV  = IV;

                // Create a decryptor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            // Read the decrypted bytes from the decrypting stream and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
            }
            return(plaintext);
        }
        private IEnumerable <InternalBulkMeasurements> Decompress(string data)
        {
            var bytes = Convert.FromBase64String(data);

            using var to   = new MemoryStream();
            using var from = new MemoryStream(bytes);
            using var gzip = new GZipStream(@from, CompressionMode.Decompress);

            gzip.CopyTo(to);
            var final             = to.ToArray();
            var protoMeasurements = MeasurementData.Parser.ParseFrom(final);
            var measurements      =
                from measurement in protoMeasurements.Measurements
                group measurement by measurement.SensorID into g
                select new InternalBulkMeasurements {
                SensorID     = ObjectId.Parse(g.Key),
                Measurements = g.Select(m => new SingleMeasurement {
                    Data = m.Datapoints.ToDictionary(p => p.Key, p => new DataPoint {
                        Accuracy  = p.Accuracy,
                        Precision = p.Precision,
                        Unit      = p.Unit,
                        Value     = Convert.ToDecimal(p.Value),
                    }),
                    Location     = new GeoJsonPoint <GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(m.Longitude, m.Latitude)),
                    PlatformTime = m.PlatformTime.ToDateTime(),
                    Timestamp    = m.Timestamp.ToDateTime()
                }).ToList()
            };

            this.logger.LogInformation("Received {count} measurements.", protoMeasurements.Measurements.Count);
            return(measurements);
        }
        public static string Decrypt(this string encryptedText)
        {
            if (!IsEncrypted(encryptedText))
            {
                return(encryptedText);
            }

            var cipherTextBytes = Convert.FromBase64String(encryptedText.Substring(ENCRYPTION_INDICATOR.Length));
            var keyBytes        = new Rfc2898DeriveBytes(PASSWORD_HASH, ASCII.GetBytes(SALT_KEY)).GetBytes(256 / 8);
            var symmetricKey    = new RijndaelManaged()
            {
                Mode = CipherMode.CBC, Padding = PaddingMode.None
            };

            var decryptor = symmetricKey.CreateDecryptor(keyBytes, ASCII.GetBytes(VI_KEY));

            using (var memoryStream = new MemoryStream(cipherTextBytes))
            {
                var plainTextBytes = new byte[cipherTextBytes.Length];
                using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                {
                    var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                    return(UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray()));
                }
            }
        }
Ejemplo n.º 4
0
    //AES_256 복호화
    static private string ProcDecrypt_AES256(string InputText)
    {
        RijndaelManaged RijndaelCipher = new RijndaelManaged();

        byte[] EncryptedData = Convert.FromBase64String(InputText);
        byte[] Salt          = Encoding.ASCII.GetBytes(const_strPasswordKey.Length.ToString());

        PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(const_strPasswordKey, Salt);

        // Decryptor 객체를 만든다.
        ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));

        MemoryStream memoryStream = new MemoryStream(EncryptedData);

        // 데이터 읽기 용도의 cryptoStream객체
        CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);

        // 복호화된 데이터를 담을 바이트 배열을 선언한다.
        byte[] PlainText = new byte[EncryptedData.Length];

        int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);

        memoryStream.Close();
        cryptoStream.Close();

        string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);

        return(DecryptedData);
    }
        public static byte[] SecureStringToBytesBase64Decode(SecureString s)
        {
            string unsecure = SecureStringToString(s);

            byte[] bytes = Convert.FromBase64String(unsecure);
            unsecure = null;
            return(bytes);
        }
Ejemplo n.º 6
0
        public Image DeserializeImage(string name)
        {
            JToken imageToken = _json["Images"][name];

            var base64String = imageToken.ToString();

            byte[] data = Convert.FromBase64String(base64String);
            using (var stream = new MemoryStream(data, 0, data.Length))
            {
                Image image = Image.FromStream(stream);
                image.Tag = name;
                return(image);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Decodes the stored string to normal text.
        /// </summary>
        /// <returns>The decoded string.</returns>
        public string Decode()
        {
            if (encoded)
            {
                text = UTF8.GetString(Convert.FromBase64String(text));
            }
            else
            {
                throw new InvalidOperationException("Cannot decode an already decoded string");
            }

            encoded = false;
            return(text);
        }
Ejemplo n.º 8
0
        public static string DecryptString(string stringToDecrypt)
        {
            string decrypted;

            try
            {
                var b = Convert.FromBase64String(stringToDecrypt);
                decrypted = ASCII.GetString(b);
            }
            catch (FormatException)
            {
                decrypted = "";
            }
            return(decrypted);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// DSE解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string GetDesDecode(string str)
        {
            byte[] byKey = UTF8.GetBytes(KEY_64);
            byte[] byIV  = UTF8.GetBytes(IV_64);
            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(str);
            }
            catch
            {
                return(null);
            }
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream             ms             = new MemoryStream(byEnc);
            CryptoStream             cst            = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader             sr             = new StreamReader(cst);

            return(sr.ReadToEnd());
        }
Ejemplo n.º 10
0
        protected virtual void AddSyncField(BulkLoadContext context, BulkLoadItem bulkItem, IItemFieldValue itemField,
                                            string language = null, int versionNumber = 1)
        {
            var fieldId    = itemField.FieldId;
            var fieldValue = itemField.Value;
            var fieldName  = itemField.NameHint;
            var isBlob     = itemField.BlobId.HasValue;

            Func <Stream> blob = null;

            if (isBlob)
            {
                byte[] blobBytes;
                try
                {
                    blobBytes = Convert.FromBase64String(fieldValue);
                }
                catch (Exception ex)
                {
                    blobBytes = new byte[] { };
                    context.Log.Error(
                        $"Unable to read blob from field '{fieldId}' in item with id '{bulkItem.Id}', " +
                        $"item path '{bulkItem.ParentId}' and source info '{bulkItem.SourceInfo}', defaulting to empty value.",
                        ex);
                }
                blob = () => new MemoryStream(blobBytes);

                // Field value needs to be set to the blob id.
                fieldValue = itemField.BlobId.Value.ToString("B").ToUpper();
            }

            if (language == null)
            {
                bulkItem.AddSharedField(fieldId, fieldValue, blob, isBlob, fieldName);
            }
            else
            {
                bulkItem.AddVersionedField(fieldId, language, versionNumber, fieldValue, blob, isBlob, fieldName);
            }
        }
Ejemplo n.º 11
0
        public static byte[] Encrypt(string plainText, byte[] IV)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }

            byte[] encrypted;

            // Create an Aes object with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key  = Convert.FromBase64String(_key);
                aesAlg.IV   = IV;
                aesAlg.Mode = CipherMode.CBC;
                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
            }

            // Return the encrypted bytes from the memory stream.
            return(encrypted);
        }
Ejemplo n.º 12
0
 public static byte[] DecodeToBytes(string base64) =>
 Convert.FromBase64String(base64.Replace('-', '+').Replace('_', '/'));
Ejemplo n.º 13
0
 public static string Decode(string textFormat)
 {
     return(UTF8.GetString(Convert.FromBase64String(textFormat)));
 }
Ejemplo n.º 14
0
 // decode
 public string Decode()
 {
     text = UTF8.GetString(Convert.FromBase64String(text));
     return(text);
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Inserts field value into item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="field">The field.</param>
        /// <param name="creatingNewItem">Whether the item under update is new or not (controls logging verbosity)</param>
        /// <exception cref="T:Sitecore.Data.Serialization.Exceptions.FieldIsMissingFromTemplateException"/>
        protected virtual bool PasteField(Item item, IItemFieldValue field, bool creatingNewItem)
        {
            if (!_fieldFilter.Includes(field.FieldId))
            {
                _logger.SkippedPastingIgnoredField(item, field);
                return(false);
            }

            Template template = AssertTemplate(item.Database, item.TemplateID, item.Paths.Path);

            if (template.GetField(new ID(field.FieldId)) == null)
            {
                item.Database.Engines.TemplateEngine.Reset();
                template = AssertTemplate(item.Database, item.TemplateID, item.Paths.Path);
            }

            if (template.GetField(new ID(field.FieldId)) == null)
            {
                throw new TemplateMissingFieldException(item.TemplateName, item.Database.Name + ":" + item.Paths.FullPath, field);
            }

            Field itemField = item.Fields[new ID(field.FieldId)];

            if (itemField.IsBlobField)
            {
                Guid existingBlobId;
                bool hasExistingId = Guid.TryParse(itemField.Value, out existingBlobId);

                // serialized blob has no value (media item with detached media)
                if (!field.BlobId.HasValue)
                {
                    if (!hasExistingId || existingBlobId == Guid.Empty)
                    {
                        return(false);                                                                    // no blob ID and none in DB either, so we're cool
                    }
                    // existing blob in DB but none in serialized
                    // so clear the blob and field value
                    ItemManager.RemoveBlobStream(existingBlobId, item.Database);
                    itemField.SetValue(string.Empty, true);
                    _logger.WroteBlobStream(item, field);

                    return(true);
                }

                // check if existing blob is here with the same ID; abort if so
                if (hasExistingId && existingBlobId == field.BlobId.Value)
                {
                    return(false);
                }

                byte[] buffer = Convert.FromBase64String(field.Value);

                // if an existing blob of a different ID exists, drop it from the database
                if (existingBlobId != default(Guid))
                {
                    ItemManager.RemoveBlobStream(existingBlobId, item.Database);
                }

                // write the new blob to the database
                ItemManager.SetBlobStream(new MemoryStream(buffer, false), field.BlobId.Value, item.Database);

                // set the value of the blob field to the correct blob ID
                itemField.SetValue(MainUtil.GuidToString(field.BlobId.Value), true);

                if (!creatingNewItem)
                {
                    _logger.WroteBlobStream(item, field);
                }

                return(true);
            }

            if (field.Value != null && !field.Value.Equals(itemField.GetValue(false, false)))
            {
                var oldValue = itemField.Value;
                itemField.SetValue(field.Value, true);

                if (!creatingNewItem)
                {
                    _logger.UpdatedChangedFieldValue(item, field, oldValue);
                }

                return(true);
            }

            return(false);
        }
Ejemplo n.º 16
0
        /// <summary>
        ///  解码
        /// </summary>
        /// Author  : Napoleon
        /// Created : 2015-05-26 15:07:25
        private string DecodeFunc(string decodeValue, string decodeFunc)
        {
            string result = "";

            try
            {
                switch (decodeFunc)
                {
                case "Default":
                    result = HttpUtility.UrlDecode(decodeValue, Encoding.Default);
                    break;

                case "UTF32":
                    result = HttpUtility.UrlDecode(decodeValue, Encoding.UTF32);
                    break;

                case "UTF8":
                    result = HttpUtility.UrlDecode(decodeValue, Encoding.UTF8);
                    break;

                case "UTF7":
                    result = HttpUtility.UrlDecode(decodeValue, Encoding.UTF7);
                    break;

                case "Unicode":
                    result = HttpUtility.UrlDecode(decodeValue, Encoding.Unicode);
                    break;

                case "ASCII":
                    result = HttpUtility.UrlDecode(decodeValue, Encoding.ASCII);
                    break;

                case "Base64":
                    result = Encoding.Default.GetString(Convert.FromBase64String(decodeValue));
                    break;

                case "GBK":    //简体中文
                    result = HttpUtility.UrlDecode(decodeValue, Encoding.GetEncoding("GBK"));
                    break;

                case "GB2312":    //简体中文
                    result = HttpUtility.UrlDecode(decodeValue, Encoding.GetEncoding("GB2312"));
                    break;

                case "GB18030":    //繁体中文
                    result = HttpUtility.UrlDecode(decodeValue, Encoding.GetEncoding("GB18030"));
                    break;

                case "escape":    //js的编码
                    result = GlobalObject.escape(decodeValue);
                    break;

                case "encodeURI":
                    result = GlobalObject.decodeURI(decodeValue);
                    break;

                case "encodeURIComponent":
                    result = GlobalObject.decodeURIComponent(decodeValue);
                    break;
                }
            }
            catch (Exception exception)
            {
                result = exception.Message;
            }
            return(result);
        }
        public ActionResult <bool> EvaluateStudents([FromBody] List <Evaluation> evaluations)
        {
            var dao = new EvaluationsDao();

            Directory.CreateDirectory(STUDENT_ANS_SHEET_UPLOAD_PATH);
            foreach (var e in evaluations)
            {
                Console.WriteLine("-------------------------------------------------------");
                Console.WriteLine($"Student Id {e.Student.Id}");
                Console.WriteLine($"DateTime {e.DateTime?.ToString("yyyy-MM-dd")}");
                var date     = e.DateTime?.ToString("yyyy_MM_dd");
                var fileName = $"AnswerKey_Student_{e.Student.Id}_{e.Examination.Course.CourseCode}_{date}.pdf";
                var filePath = Path.Combine(STUDENT_ANS_SHEET_UPLOAD_PATH, fileName);
                var bytes    = Convert.FromBase64String(e.AnswerSheet);
                System.IO.File.WriteAllBytes(filePath, bytes);
                Console.WriteLine("File Written");

                var refSheetName =
                    e.Examination.ReferenceAnswerSheet.Substring(
                        e.Examination.ReferenceAnswerSheet.LastIndexOf("/") + 1);

                var refSheetPath = Path.Combine(REFERENCE_ANS_SHEET_UPLOAD_PATH, refSheetName);
                Console.WriteLine($"Ref Sheet Path = {refSheetPath}");

                var studentPdf = new PdfFocus();
                Console.WriteLine($"Opening Student Pdf...");
                studentPdf.OpenPdf(filePath);
                var studentAnsText = studentPdf.ToText();
                Console.WriteLine("Student pdf read successfully!");
                studentPdf.ClosePdf();
                Console.WriteLine("Closing student pdf");

                var refPdf = new PdfFocus();
                Console.WriteLine("Opening reference pdf");
                refPdf.OpenPdf(refSheetPath);
                var refAnsText = refPdf.ToText();
                Console.WriteLine("Reference pdf read successfully!");
                refPdf.ClosePdf();
                Console.WriteLine("Closing reference pdf");

                paralleldots pd = new paralleldots("AliC73YnPPScR8dJJEMD8qxinhFTTUjFPmJGs5yknY0");
                Console.WriteLine("Calculating score");
                var similarity = pd.similarity(studentAnsText, refAnsText);

                var json  = JsonValue.Parse(similarity);
                var score = double.Parse(json["normalized_score"].ToString());
                Console.WriteLine($"Score = {score}");
                var percent = score / 5.0;
                Console.WriteLine($"Percentage = {percent}");

                e.MarksObtained = (int?)(e.Examination.TotalMarks * percent);

                e.AnswerSheet = $"/api/examinations/student-ans-sheet/get/{fileName}";

                Console.WriteLine("Writing result to database");
                dao.CreateEvaluation(e);
                Console.WriteLine("Written Successfully!");
            }

            return(true);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Inserts field value into item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="field">The field.</param>
        /// <param name="creatingNewItem">Whether the item under update is new or not (controls logging verbosity)</param>
        /// <exception cref="T:Sitecore.Data.Serialization.Exceptions.FieldIsMissingFromTemplateException"/>
        protected virtual bool PasteField(Item item, IItemFieldValue field, bool creatingNewItem)
        {
            if (!_fieldFilter.Includes(field.FieldId))
            {
                _logger.SkippedPastingIgnoredField(item, field);
                return(false);
            }

            Template template = AssertTemplate(item.Database, item.TemplateID, item.Paths.Path);

            if (template.GetField(new ID(field.FieldId)) == null)
            {
                item.Database.Engines.TemplateEngine.Reset();
                template = AssertTemplate(item.Database, item.TemplateID, item.Paths.Path);
            }

            if (template.GetField(new ID(field.FieldId)) == null)
            {
                throw new TemplateMissingFieldException(item.TemplateName, item.Database.Name + ":" + item.Paths.FullPath, field);
            }

            Field itemField = item.Fields[new ID(field.FieldId)];

            if (itemField.IsBlobField)
            {
                if (!field.BlobId.HasValue)
                {
                    throw new InvalidOperationException("Field " + field.FieldId + " is a blob field, but it had no blob ID.");
                }

                // check if existing blob is here with the same ID; abort if so
                Guid existingBlobId;
                if (Guid.TryParse(itemField.Value, out existingBlobId) && existingBlobId == field.BlobId.Value)
                {
                    return(false);
                }

                byte[] buffer = Convert.FromBase64String(field.Value);

                // if an existing blob of a different ID exists, drop it from the database
                if (existingBlobId != default(Guid))
                {
                    ItemManager.RemoveBlobStream(existingBlobId, item.Database);
                }

                // write the new blob to the database
                ItemManager.SetBlobStream(new MemoryStream(buffer, false), field.BlobId.Value, item.Database);

                // set the value of the blob field to the correct blob ID
                itemField.SetValue(MainUtil.GuidToString(field.BlobId.Value), true);

                if (!creatingNewItem)
                {
                    _logger.WroteBlobStream(item, field);
                }

                return(true);
            }

            if (field.Value != null && !field.Value.Equals(itemField.GetValue(false, false)))
            {
                var oldValue = itemField.Value;
                itemField.SetValue(field.Value, true);

                if (!creatingNewItem)
                {
                    _logger.UpdatedChangedFieldValue(item, field, oldValue);
                }

                return(true);
            }

            return(false);
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Static decoding, decodes a base64 string to a normal one.
 /// </summary>
 /// <param name="text">The base64 string to decode.</param>
 /// <returns>The decoded string.</returns>
 public static string Decode(string base64) =>
 UTF8.GetString(Convert.FromBase64String(base64.Replace('-', '+').Replace('_', '/')));
Ejemplo n.º 20
0
 public static byte[] Encrypt(string plainText, string base64Iv)
 {
     return(Encrypt(plainText, Convert.FromBase64String(base64Iv)));
 }
Ejemplo n.º 21
0
 /// <summary>
 /// Static decoding, decodes a base64 string to a normal one.
 /// </summary>
 /// <param name="text">The base64 string to decode.</param>
 /// <returns>The decoded string.</returns>
 public static string Decode(string base64) =>
 UTF8.GetString(Convert.FromBase64String(base64));
Ejemplo n.º 22
0
 public static byte[] Encrypt(string plainText)
 {
     return(Encrypt(plainText, Convert.FromBase64String(IvForGeneralPurpose)));
 }
Ejemplo n.º 23
0
 private static byte[] GetBytesFromBase64Guid(string source)
 {
     return(Convert.FromBase64String(source.Replace("_", "/").Replace("-", "+")));
 }
Ejemplo n.º 24
0
 public static string Decrypt(string base64CipherText)
 {
     return(Decrypt(Convert.FromBase64String(base64CipherText), Convert.FromBase64String(IvForGeneralPurpose)));
 }
Ejemplo n.º 25
0
 public static string Decrypt(string base64CipherText, string base64Iv)
 {
     return(Decrypt(Convert.FromBase64String(base64CipherText), Convert.FromBase64String(base64Iv)));
 }
Ejemplo n.º 26
0
 public static byte[] DecodeToBytes(string base64) =>
 Convert.FromBase64String(base64);
Ejemplo n.º 27
0
        public static string DecodeCredentials(string credential)
        {
            var decodedAuth = UTF8.GetString(Convert.FromBase64String(credential));

            return(decodedAuth);
        }