Пример #1
0
        public static string ComputeId(Tree tree)
        {
            using (var md = new MessageDigest())
            {
                using (var ms = new MemoryStream())
                {
                    foreach (var item in tree.Items)
                    {
                        var data = Encoding.Default.GetBytes(string.Format("{0} {1}\0", item.Mode, item.Name));
                        ms.Write(data, 0, data.Length);

                        var id = Helper.IdToByteArray(item.Id);
                        ms.Write(id, 0, id.Length);
                    }

                    var header = Encoding.Default.GetBytes(string.Format("tree {0}\0", ms.Length));
                    ms.Position = 0;
                    md.Update(header);
                    md.Update(ms);
                }
                var digest = md.Digest();

                return Helper.ByteArrayToId(digest);
            }
        }
Пример #2
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            // Create callback manager using CallbackManagerFactory
            CallbackManager = CallbackManagerFactory.Create();
            CachedImageRenderer.Init(enableFastRenderer: true);

            base.OnCreate(savedInstanceState);
            CachedImageRenderer.Init(enableFastRenderer: true);

            global::Xamarin.Forms.Forms.SetFlags("Shell_Experimental", "Visual_Experimental", "CollectionView_Experimental", "FastRenderers_Experimental");
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            Xamarin.FormsMaps.Init(this, savedInstanceState);
            Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, savedInstanceState);
            //LoadApplication(new App(Services.SharedInstance));

            try
            {
                PackageInfo info = PackageManager.GetPackageInfo(
                    "com.companyname.App1",
                    PackageInfoFlags.Signatures);
                foreach (var signature in info.Signatures)
                {
                    MessageDigest md = MessageDigest.GetInstance("SHA");
                    md.Update(signature.ToByteArray());
                    Log.Debug("KeyHash:", Base64.EncodeToString(md.Digest(), Base64.Default));
                    var s = Base64.EncodeToString(md.Digest(), Base64.Default);
                }
            }
            catch (NameNotFoundException e)
            {
            }
            catch (NoSuchAlgorithmException e)
            {
            }


            LoadApplication(new App());
        }
        /// <summary>Compute the name of an object, without inserting it.</summary>
        /// <remarks>Compute the name of an object, without inserting it.</remarks>
        /// <param name="type">type code of the object to store.</param>
        /// <param name="data">complete content of the object.</param>
        /// <param name="off">
        /// first position within
        /// <code>data</code>
        /// .
        /// </param>
        /// <param name="len">
        /// number of bytes to copy from
        /// <code>data</code>
        /// .
        /// </param>
        /// <returns>the name of the object.</returns>
        public virtual ObjectId IdFor(int type, byte[] data, int off, int len)
        {
            MessageDigest md = Digest();

            md.Update(Constants.EncodedTypeString(type));
            md.Update(unchecked ((byte)' '));
            md.Update(Constants.EncodeASCII(len));
            md.Update(unchecked ((byte)0));
            md.Update(data, off, len);
            return(ObjectId.FromRaw(md.Digest()));
        }
Пример #4
0
        public void EmptyString()
        {
            var expected = new byte[] { 256 - 44, 29, 256 - 116, 256 - 39, 256 - 113, 0, 256 - 78, 4, 256 - 23, 256 - 128, 9, 256 - 104, 256 - 20, 256 - 8, 66, 126 };

            MessageDigest md = CreateSUT();

            byte[] result = md.Digest();

            Assert.AreEqual(16, result.Length);
            Assert.IsTrue(expected.SequenceEqual(result));
        }
Пример #5
0
        public void EmptyString()
        {
            var expected = new byte[] { 256 - 38, 57, 256 - 93, 256 - 18, 94, 107, 75, 13, 50, 85, 256 - 65, 256 - 17, 256 - 107, 96, 24, 256 - 112, 256 - 81, 256 - 40, 7, 9 };

            MessageDigest md = CreateSUT();

            byte[] result = md.Digest();

            Assert.AreEqual(20, result.Length);
            Assert.IsTrue(expected.SequenceEqual(result));
        }
Пример #6
0
        public ObjectId computeName()
        {
            MessageDigest md = Constants.newMessageDigest();

            foreach (ObjectToPack otp in sortByName())
            {
                otp.copyRawTo(_buf, 0);
                md.Update(_buf, 0, Constants.OBJECT_ID_LENGTH);
            }
            return(ObjectId.FromRaw(md.Digest()));
        }
Пример #7
0
        /// <summary>Construct a hash value for the content from the InputStream.</summary>
        /// <exception cref="System.IO.IOException"/>
        public static Org.Apache.Hadoop.IO.MD5Hash Digest(InputStream @in)
        {
            byte[]        buffer   = new byte[4 * 1024];
            MessageDigest digester = GetDigester();

            for (int n; (n = @in.Read(buffer)) != -1;)
            {
                digester.Update(buffer, 0, n);
            }
            return(new Org.Apache.Hadoop.IO.MD5Hash(digester.Digest()));
        }
Пример #8
0
        public void ShortStringOneUpdate()
        {
            var expected = new byte[] { 101, 256 - 19, 26, 256 - 3, 85, 256 - 19, 125, 33, 256 - 20, 256 - 96, 256 - 100, 256 - 24, 256 - 54, 69, 256 - 87, 14 };

            MessageDigest md = CreateSUT();

            md.Update("nulltoken".getBytes());
            byte[] result = md.Digest();

            Assert.AreEqual(16, result.Length);
            Assert.IsTrue(expected.SequenceEqual(result));
        }
Пример #9
0
 private static byte[] getKeyHash(Certificate signerCert)
 {
     try
     {
         MessageDigest sha256 = MessageDigest.GetInstance("SHA-256");
         return(sha256.Digest(signerCert.PublicKey.GetEncoded()));
     }
     catch (NoSuchAlgorithmException e)
     {
         throw new UnsupportedCryptoPrimitiveException("SHA-256 not supported: " + e.Message, e);
     }
 }
Пример #10
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            var density = Resources.DisplayMetrics.Density;

            App.screenWidth  = Resources.DisplayMetrics.WidthPixels / density;
            App.screenHeight = Resources.DisplayMetrics.HeightPixels / density;

            if (Xamarin.Forms.Device.Idiom == TargetIdiom.Phone)
            {
                App.screenHeight = (16 * App.screenWidth) / 9;
            }

            if (Xamarin.Forms.Device.Idiom == TargetIdiom.Tablet)
            {
                App.screenWidth = (9 * App.screenHeight) / 16;
            }

            try
            {
                PackageInfo info = Android.App.Application.Context.PackageManager.GetPackageInfo(Android.App.Application.Context.PackageName, PackageInfoFlags.Signatures);
                foreach (var signature in info.Signatures)
                {
                    MessageDigest md = MessageDigest.GetInstance("SHA");
                    md.Update(signature.ToByteArray());
                    System.Diagnostics.Debug.WriteLine("helloWorld");
                    System.Diagnostics.Debug.WriteLine(Convert.ToBase64String(md.Digest()));
                }
            }
            catch (NoSuchAlgorithmException e)
            {
                System.Diagnostics.Debug.WriteLine(e);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e);
            }

            PrintHashKey(this);

            FacebookSdk.ApplicationId = "244197793511500";
            FacebookSdk.SdkInitialize(this);
            FacebookClientManager.Initialize(this);
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;
            FirebaseApp.InitializeApp(this);
            base.OnCreate(savedInstanceState);

            GoogleClientManager.Initialize(this);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
Пример #11
0
        /// <summary>Call this after all the data has been added.</summary>
        public void Finish()
        {
            try {
                outStream.Flush();
                outStream.Close();
            } catch (IOException e) {
                Log.W(Database.TAG, "Exception closing output stream", e);
            }

            blobKey         = new BlobKey(sha1Digest.Digest());
            md5DigestResult = md5Digest.Digest();
        }
Пример #12
0
        public void ShortStringOneUpdate()
        {
            var expected = new byte[] { 48, 15, 76, 31, 256 - 27, 18, 256 - 16, 66, 256 - 67, 256 - 20, 8, 70, 256 - 23, 114, 104, 256 - 49, 113, 97, 55, 256 - 65 };

            MessageDigest md = CreateSUT();

            md.Update("nulltoken".getBytes());
            byte[] result = md.Digest();

            Assert.AreEqual(20, result.Length);
            Assert.IsTrue(expected.SequenceEqual(result));
        }
Пример #13
0
 public virtual byte[] Digest()
 {
     byte[] b;
     b = _digest.Digest();
     if (Log.Level >= 5)
     {
         Log.WriteLine("digest: ");
         Hexdump.ToHexdump(Log, b, 0, b.Length);
     }
     _updates = 0;
     return(b);
 }
Пример #14
0
        /// <summary>Call this after all the data has been added.</summary>
        public void Finish()
        {
            try {
                outStream.Flush();
                outStream.Dispose();
            } catch (IOException e) {
                Log.To.Database.W(Tag, "Exception closing output stream, continuing...", e);
            }

            blobKey         = new BlobKey(sha1Digest.Digest());
            md5DigestResult = md5Digest.Digest();
        }
Пример #15
0
 private static string H(string data)
 {
     try
     {
         MessageDigest md = NewMD5();
         md.Update(Sharpen.Runtime.GetBytesForString(data, "UTF-8"));
         return(Lhex(md.Digest()));
     }
     catch (UnsupportedEncodingException e)
     {
         throw new RuntimeException("UTF-8 encoding not available", e);
     }
 }
Пример #16
0
 /// <summary>Call this after all the data has been added.</summary>
 /// <remarks>Call this after all the data has been added.</remarks>
 public virtual void Finish()
 {
     try
     {
         outStream.Close();
     }
     catch (IOException e)
     {
         Log.W(Log.TagBlobStore, "Exception closing output stream", e);
     }
     blobKey         = new BlobKey(sha1Digest.Digest());
     md5DigestResult = md5Digest.Digest();
 }
Пример #17
0
            /// <exception cref="System.IO.IOException"/>
            private void SaveInternal(FileOutputStream fout, FSImageCompression compression,
                                      string filePath)
            {
                StartupProgress prog     = NameNode.GetStartupProgress();
                MessageDigest   digester = MD5Hash.GetDigester();

                underlyingOutputStream = new DigestOutputStream(new BufferedOutputStream(fout), digester
                                                                );
                underlyingOutputStream.Write(FSImageUtil.MagicHeader);
                fileChannel = fout.GetChannel();
                FsImageProto.FileSummary.Builder b = FsImageProto.FileSummary.NewBuilder().SetOndiskVersion
                                                         (FSImageUtil.FileVersion).SetLayoutVersion(NameNodeLayoutVersion.CurrentLayoutVersion
                                                                                                    );
                codec = compression.GetImageCodec();
                if (codec != null)
                {
                    b.SetCodec(codec.GetType().GetCanonicalName());
                    sectionOutputStream = codec.CreateOutputStream(underlyingOutputStream);
                }
                else
                {
                    sectionOutputStream = underlyingOutputStream;
                }
                SaveNameSystemSection(b);
                // Check for cancellation right after serializing the name system section.
                // Some unit tests, such as TestSaveNamespace#testCancelSaveNameSpace
                // depends on this behavior.
                context.CheckCancelled();
                Step step = new Step(StepType.Inodes, filePath);

                prog.BeginStep(Phase.SavingCheckpoint, step);
                SaveInodes(b);
                SaveSnapshots(b);
                prog.EndStep(Phase.SavingCheckpoint, step);
                step = new Step(StepType.DelegationTokens, filePath);
                prog.BeginStep(Phase.SavingCheckpoint, step);
                SaveSecretManagerSection(b);
                prog.EndStep(Phase.SavingCheckpoint, step);
                step = new Step(StepType.CachePools, filePath);
                prog.BeginStep(Phase.SavingCheckpoint, step);
                SaveCacheManagerSection(b);
                prog.EndStep(Phase.SavingCheckpoint, step);
                SaveStringTableSection(b);
                // We use the underlyingOutputStream to write the header. Therefore flush
                // the buffered stream (which is potentially compressed) first.
                FlushSectionOutputStream();
                FsImageProto.FileSummary summary = ((FsImageProto.FileSummary)b.Build());
                SaveFileSummary(underlyingOutputStream, summary);
                underlyingOutputStream.Close();
                savedDigest = new MD5Hash(digester.Digest());
            }
        private void VerifyLooseObject(AnyObjectId id, byte[] compressed)
        {
            UnpackedObjectLoader uol;

            try
            {
                uol = new UnpackedObjectLoader(compressed);
            }
            catch (CorruptObjectException parsingError)
            {
                // Some HTTP servers send back a "200 OK" status with an HTML
                // page that explains the requested file could not be found.
                // These servers are most certainly misconfigured, but many
                // of them exist in the world, and many of those are hosting
                // Git repositories.
                //
                // Since an HTML page is unlikely to hash to one of our loose
                // objects we treat this condition as a FileNotFoundException
                // and attempt to recover by getting the object from another
                // source.
                //
                var e = new FileNotFoundException(id.Name, parsingError);
                throw e;
            }

            _objectDigest.Reset();
            _objectDigest.Update(Constants.encodedTypeString(uol.Type));
            _objectDigest.Update((byte)' ');
            _objectDigest.Update(Constants.encodeASCII(uol.Size));
            _objectDigest.Update(0);
            _objectDigest.Update(uol.CachedBytes);
            _idBuffer.FromRaw(_objectDigest.Digest(), 0);

            if (!AnyObjectId.equals(id, _idBuffer))
            {
                throw new TransportException("Incorrect hash for " + id.Name + "; computed " + _idBuffer.Name + " as a " +
                                             Constants.typeString(uol.Type) + " from " + compressed.Length +
                                             " bytes.");
            }
            if (_objCheck != null)
            {
                try
                {
                    _objCheck.check(uol.Type, uol.CachedBytes);
                }
                catch (CorruptObjectException e)
                {
                    throw new TransportException("Invalid " + Constants.typeString(uol.Type) + " " + id.Name + ": " + e.Message);
                }
            }
        }
Пример #19
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            ActivityContext = this;

            FacebookClientManager.Initialize(this);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            Rg.Plugins.Popup.Popup.Init(this, savedInstanceState);
            Xamarin.FormsMaps.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            AiForms.Dialogs.Dialogs.Init(this);
            LoadApplication(new App());

            try
            {
                PackageInfo info = Android.App.Application.Context.PackageManager.GetPackageInfo(Android.App.Application.Context.PackageName, PackageInfoFlags.Signatures);
                foreach (var signature in info.Signatures)
                {
                    MessageDigest md = MessageDigest.GetInstance("SHA");
                    md.Update(signature.ToByteArray());
                    string shahuella = Convert.ToBase64String(md.Digest());
                    System.Diagnostics.Debug.WriteLine(Convert.ToBase64String(md.Digest()));
                }
            }
            catch (NoSuchAlgorithmException e)
            {
                System.Diagnostics.Debug.WriteLine(e);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e);
            }
        }
Пример #20
0
        public static string ComputeId(Blob blob)
        {
            using (var md = new MessageDigest())
            {
                byte[] data = Encoding.Default.GetBytes(string.Format("blob {0}\0", blob.Size));

                md.Update(data);
                md.Update(blob.Data);

                var digest = md.Digest();

                return Helper.ByteArrayToId(digest);
            }
        }
Пример #21
0
        /**
         * Construct LogSignatureVerifiers for each of the trusted CT logs.
         *
         * @throws InvalidKeySpecException the CT log key isn't RSA or EC, the key is probably corrupt.
         * @throws NoSuchAlgorithmException the crypto provider couldn't supply the hashing algorithm or
         *     the key algorithm. This probably means you are using an ancient or bad crypto provider.
         */
        private void buildLogSignatureVerifiers()
        {
            MessageDigest hasher = MessageDigest.GetInstance(LOG_ID_HASH_ALGORITHM);

            foreach (string trustedLogKey in TRUSTED_LOG_KEYS)
            {
                hasher.Reset();
                byte[]     keyBytes   = Base64.Decode(trustedLogKey);
                string     logId      = Base64.ToBase64String(hasher.Digest(keyBytes));
                KeyFactory keyFactory = KeyFactory.GetInstance(determineKeyAlgorithm(keyBytes));
                var        publicKey  = keyFactory.GeneratePublic(new X509EncodedKeySpec(keyBytes));
                verifiers.Add(logId, new LogSignatureVerifier(new LogInfo(publicKey)));
            }
        }
Пример #22
0
        protected static byte[] FillAndXor(byte[] hash, byte FillByte)
        {
            byte[] buff = new byte[64];
            Arrays.Fill(buff, FillByte);

            for (int i = 0; i < hash.Length; i++)
            {
                buff[i] = (byte)(buff[i] ^ hash[i]);
            }

            MessageDigest sha1 = CryptoFunctions.GetMessageDigest(HashAlgorithm.sha1);

            return(sha1.Digest(buff));
        }
Пример #23
0
 /// <exception cref="Sharpen.DigestException"/>
 private long MD5Hashcode(byte[] bytes, int start, int length)
 {
     lock (this)
     {
         Digester.Update(bytes, 0, length);
         Digester.Digest(digest, 0, Md5Len);
         long hashcode = 0;
         for (int i = 0; i < 8; i++)
         {
             hashcode |= ((digest[i] & unchecked ((long)(0xffL))) << (8 * (7 - i)));
         }
         return(hashcode);
     }
 }
Пример #24
0
        protected internal static ISecretKey GenerateSecretKey(String password, EncryptionVerifier ver)
        {
            if (password.Length > 255)
            {
                password = password.Substring(0, 255);
            }
            HashAlgorithm hashAlgo = ver.HashAlgorithm;
            MessageDigest hashAlg  = CryptoFunctions.GetMessageDigest(hashAlgo);

            hashAlg.Update(ver.Salt);
            byte[]     hash = hashAlg.Digest(StringUtil.GetToUnicodeLE(password));
            ISecretKey skey = new SecretKeySpec(hash, ver.CipherAlgorithm.jceId);

            return(skey);
        }
Пример #25
0
        public void getAndroidKey()
        {
            PackageInfo info = this.PackageManager.GetPackageInfo("com.ihbi.project", PackageInfoFlags.Signatures);

            foreach (Android.Content.PM.Signature signature in info.Signatures)
            {
                //System.Diagnostics.Debug.WriteLine("Sig: "+ signature.ToString ());
                MessageDigest md = MessageDigest.GetInstance("SHA");

                md.Update(signature.ToByteArray());

                string keyhash = Convert.ToBase64String(md.Digest());
                System.Diagnostics.Debug.WriteLine("KeyHash:" + keyhash);
            }
        }
Пример #26
0
        public static string HashBytes(byte[] data)
        {
            MessageDigest md = MessageDigest.GetInstance("SHA-256");

            md.Update(data);
            byte[]        digest     = md.Digest();
            StringBuilder hashString = new StringBuilder();

            foreach (var @byte in digest)
            {
                hashString.Append(@byte.ToString("x2"));
            }

            return(hashString.ToString());
        }
Пример #27
0
 /// <exception cref="System.Exception"></exception>
 public virtual void Init(byte[] key)
 {
     if (key.Length > bsize)
     {
         byte[] tmp = new byte[bsize];
         System.Array.Copy(key, 0, tmp, 0, bsize);
         key = tmp;
     }
     if (key.Length > B)
     {
         md.Update(key, 0, key.Length);
         key = md.Digest();
     }
     k_ipad = new byte[B];
     System.Array.Copy(key, 0, k_ipad, 0, key.Length);
     k_opad = new byte[B];
     System.Array.Copy(key, 0, k_opad, 0, key.Length);
     for (int i = 0; i < B; i++)
     {
         k_ipad[i] ^= unchecked ((byte)unchecked ((int)(0x36)));
         k_opad[i] ^= unchecked ((byte)unchecked ((int)(0x5c)));
     }
     md.Update(k_ipad, 0, B);
 }
Пример #28
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            PackageInfo info = this.PackageManager.GetPackageInfo("com.Devarn.x15MinuteGoals", PackageInfoFlags.Signatures);

            foreach (Android.Content.PM.Signature signs in info.Signatures)
            {
                MessageDigest md = MessageDigest.GetInstance("SHA");
                md.Update(signs.ToByteArray());
                string keyhash = Convert.ToBase64String(md.Digest());
                Console.WriteLine("Hash:{0}", keyhash);
            }
        }
Пример #29
0
 public static byte[] sha256Raw(byte[] bytes)
 {
     byte[] hash = null;
     try
     {
         MessageDigest sha = MessageDigest.GetInstance("SHA-256"); // may need to hex digest
         sha.Update(bytes);
         hash = sha.Digest();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
         Console.Write(ex.StackTrace);
     }
     return(hash);
 }
Пример #30
0
 /// <exception cref="System.IO.IOException"></exception>
 public override ObjectId Insert(int type, long len, InputStream @is)
 {
     if (len <= Buffer().Length)
     {
         byte[] buf    = Buffer();
         int    actLen = IOUtil.ReadFully(@is, buf, 0);
         return(Insert(type, buf, 0, actLen));
     }
     else
     {
         MessageDigest md  = Digest();
         FilePath      tmp = ToTemp(md, type, len, @is);
         ObjectId      id  = ObjectId.FromRaw(md.Digest());
         return(InsertOneObject(tmp, id));
     }
 }
Пример #31
0
 /// <summary>Returns then signature of a string.</summary>
 /// <param name="secret">The secret to use</param>
 /// <param name="str">string to sign.</param>
 /// <returns>the signature for the string.</returns>
 protected internal virtual string ComputeSignature(byte[] secret, string str)
 {
     try
     {
         MessageDigest md = MessageDigest.GetInstance("SHA");
         md.Update(Runtime.GetBytesForString(str, Extensions.GetEncoding("UTF-8"
                                                                         )));
         md.Update(secret);
         byte[] digest = md.Digest();
         return(new Base64(0).EncodeToString(digest));
     }
     catch (NoSuchAlgorithmException ex)
     {
         throw new RuntimeException("It should not happen, " + ex.Message, ex);
     }
 }
Пример #32
0
        /// <summary>Read dataFile and compute its MD5 checksum.</summary>
        /// <exception cref="System.IO.IOException"/>
        public static MD5Hash ComputeMd5ForFile(FilePath dataFile)
        {
            InputStream @in = new FileInputStream(dataFile);

            try
            {
                MessageDigest     digester = MD5Hash.GetDigester();
                DigestInputStream dis      = new DigestInputStream(@in, digester);
                IOUtils.CopyBytes(dis, new IOUtils.NullOutputStream(), 128 * 1024);
                return(new MD5Hash(digester.Digest()));
            }
            finally
            {
                IOUtils.CloseStream(@in);
            }
        }