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); byte[] hash = hashAlg.Digest(StringUtil.GetToUnicodeLE(password)); byte[] salt = ver.Salt; hashAlg.Reset(); for (int i = 0; i < 16; i++) { hashAlg.Update(hash, 0, 5); hashAlg.Update(salt); } hash = new byte[5]; Array.Copy(hashAlg.Digest(), 0, hash, 0, 5); ISecretKey skey = new SecretKeySpec(hash, ver.CipherAlgorithm.jceId); return(skey); }
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); } }
/// <exception cref="System.IO.IOException"></exception> public override void Write(int b) { count++; @out.Write(b); crc.Update(b); md.Update(unchecked ((byte)b)); }
private int CreateSsrc(string hostName) { try { ObjectIDGenerator obGen = new ObjectIDGenerator(); MessageDigest md = MessageDigest.GetInstance("MD5"); md.Update(Encoding.GetEncoding("UTF-8").GetBytes(Convert.ToString(new Date().Time).ToCharArray())); md.Update(Encoding.GetEncoding("UTF-8").GetBytes(Convert.ToString(obGen.ToString().ToCharArray()))); md.Update(Encoding.GetEncoding("UTF-8").GetBytes(Paths.Get("").ToAbsolutePath().Normalize().ToString().ToCharArray())); md.Update(Encoding.GetEncoding("UTF-8").GetBytes(hostName.ToCharArray())); byte[] md5 = md.Digest(); int ssrc = 0; ByteBuffer byteBuffer = ByteBuffer.Wrap(md5); for (int i = 0; i < 3; i++) { ssrc ^= byteBuffer.Int; } return(ssrc); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Could not get MD5 algorithm", e); } }
/// <summary> /// Updates the message digest (if the digest function is on) using /// the specified byte, and in any case writes the byte /// to the output stream. That is, if the digest function is on /// (see <seealso cref="#on(boolean) on"/>), this method calls /// {@code update} on the message digest associated with this /// stream, passing it the byte {@code b}. This method then /// writes the byte to the output stream, blocking until the byte /// is actually written. /// </summary> /// <param name="b"> the byte to be used for updating and writing to the /// output stream. /// </param> /// <exception cref="IOException"> if an I/O error occurs. /// </exception> /// <seealso cref= MessageDigest#update(byte) </seealso> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void write(int b) throws java.io.IOException public override void Write(int b) { @out.Write(b); if (On_Renamed) { Digest.Update((sbyte)b); } }
/// <summary> /// Reads a byte, and updates the message digest (if the digest /// function is on). That is, this method reads a byte from the /// input stream, blocking until the byte is actually read. If the /// digest function is on (see <seealso cref="#on(boolean) on"/>), this method /// will then call {@code update} on the message digest associated /// with this stream, passing it the byte read. /// </summary> /// <returns> the byte read. /// </returns> /// <exception cref="IOException"> if an I/O error occurs. /// </exception> /// <seealso cref= MessageDigest#update(byte) </seealso> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public int read() throws java.io.IOException public override int Read() { int ch = @in.Read(); if (On_Renamed && ch != -1) { Digest.Update((sbyte)ch); } return(ch); }
/// <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())); }
public void ShortStringTwoUpdates() { 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("null".getBytes()); md.Update("token".getBytes()); byte[] result = md.Digest(); Assert.AreEqual(20, result.Length); Assert.IsTrue(expected.SequenceEqual(result)); }
public void ShortStringTwoUpdates() { 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("null".getBytes()); md.Update("token".getBytes()); byte[] result = md.Digest(); Assert.AreEqual(16, result.Length); Assert.IsTrue(expected.SequenceEqual(result)); }
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); } } }
/// <summary>Appends data to the blob.</summary> /// <remarks>Appends data to the blob. Call this when new data is available.</remarks> public virtual void AppendData(byte[] data) { try { outStream.Write(data); } catch (IOException e) { throw new RuntimeException("Unable to write to stream.", e); } length += data.Length; sha1Digest.Update(data); md5Digest.Update(data); }
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); } }
/// <summary>Appends data to the blob.</summary> /// <remarks>Appends data to the blob. Call this when new data is available.</remarks> public void AppendData(IEnumerable <Byte> data) { var dataVector = data.ToArray(); length += dataVector.LongLength; sha1Digest.Update(dataVector); md5Digest.Update(dataVector); try { outStream.Write(dataVector, 0, dataVector.Length); } catch (IOException e) { throw Misc.CreateExceptionAndLog(Log.To.Database, e, Tag, "Unable to write to stream"); } }
private static string KD(string secret, string data) { try { MessageDigest md = NewMD5(); md.Update(Sharpen.Runtime.GetBytesForString(secret, "UTF-8")); md.Update(unchecked ((byte)':')); md.Update(Sharpen.Runtime.GetBytesForString(data, "UTF-8")); return(Lhex(md.Digest())); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 encoding not available", e); } }
/// <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); } }
public static string Calculate(IDictionary <string, string> components, Func <string, MessageDigest, bool> passwordDigestBlock) { MessageDigest ha1md5 = MessageDigest.GetInstance("md5"); MessageDigest ha2md5 = MessageDigest.GetInstance("md5"); MessageDigest responsemd5 = MessageDigest.GetInstance("md5"); var ha1Str = String.Format("{0}:{1}:", components.Get("username"), components.Get("realm")); ha1md5.Update(Encoding.UTF8.GetBytes(ha1Str)); if (!passwordDigestBlock(components.Get("username"), ha1md5)) { Log.To.Listener.W(TAG, "No password entered from passwordDigestBlock"); return(null); } var ha1 = BitConverter.ToString(ha1md5.Digest()).Replace("-", "").ToLowerInvariant(); var ha2Str = String.Format("{0}:{1}", components.Get("method"), components.Get("uri")); ha2md5.Update(Encoding.UTF8.GetBytes(ha2Str)); var ha2 = BitConverter.ToString(ha2md5.Digest()).Replace("-", "").ToLowerInvariant(); var responseStr = String.Format("{0}:{1}:{2}:{3}:{4}:{5}", ha1, components.Get("nonce"), components.Get("nc"), components.Get("cnonce"), components.Get("qop"), ha2); responsemd5.Update(Encoding.UTF8.GetBytes(responseStr)); return(BitConverter.ToString(responsemd5.Digest()).Replace("-", "").ToLowerInvariant()); }
protected override void OnCreate(Bundle savedInstanceState) { 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(Convert.ToBase64String(md.Digest())); } } catch (NoSuchAlgorithmException e) { System.Diagnostics.Debug.WriteLine(e); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); } TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); LoadApplication(new App()); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); uiHelper = new UiLifecycleHelper(this, callback); uiHelper.OnCreate(savedInstanceState); var info = PackageManager.GetPackageInfo("com.sammdesmond.popPIC", Android.Content.PM.PackageInfoFlags.Signatures); foreach (var signature in info.Signatures) { MessageDigest me = MessageDigest.GetInstance("SHA"); me.Update(signature.ToByteArray()); var s = Base64.EncodeToString(me.Digest(), Base64Flags.Default); Log.Error("ssl key", s); // ShowAlert ("Danny ignore this", s); } SetContentView(Resource.Layout.loginPage); loginButton = (LoginButton)FindViewById(Resource.Id.login_button); loginButton.UserInfoChangedCallback = new MyUserInfoChangedCallback(this); loginButton.LoginBehavior = SessionLoginBehavior.SsoWithFallback; greeting = FindViewById <TextView> (Resource.Id.greeting); var activeSession = Session.OpenActiveSessionFromCache(this); if (activeSession != null && activeSession.IsOpened) { // Do somethign interesting! } }
protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); FacebookSdk.SdkInitialize(this); CarouselViewRenderer.Init(); CrossCurrentActivity.Current.Init(this, bundle); FFImageLoading.Forms.Platform.CachedImageRenderer.Init(true); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); //NEDS for get correct debug keyhash PackageInfo info = this.PackageManager.GetPackageInfo("com.impressolabs.Impresso", PackageInfoFlags.Signatures); foreach (Android.Content.PM.Signature signature in info.Signatures) { MessageDigest md = MessageDigest.GetInstance("SHA"); md.Update(signature.ToByteArray()); string keyhash = Convert.ToBase64String(md.Digest()); Console.WriteLine("KeyHash:", keyhash); } }
/** Return the MD5 hash of a string. */ private String md5(String str) { // Old devices have a bug where OpenSSL can leave MessageDigest in a bad state, but trying // multiple times seems to clear it. for (int i = 0; i < 3 /** max attempts */; ++i) { try { MessageDigest _md5 = MessageDigest.GetInstance("MD5"); _md5.Update(Encoding.ASCII.GetBytes(str)); return(new BigInteger(1, _md5.Digest()).ToString(16) .ToUpper().PadLeft(32, '0')); } catch (NoSuchAlgorithmException e) { // Try again. Log.Error(TAG, e.Message); } catch (ArithmeticException ex) { Log.Error(TAG, ex.Message); return(null); } } return(null); }
protected internal static Cipher InitCipherForBlock(Cipher cipher, int block, IEncryptionInfoBuilder builder, ISecretKey skey, int encryptMode) { EncryptionVerifier ver = builder.GetVerifier(); HashAlgorithm hashAlgo = ver.HashAlgorithm; byte[] blockKey = new byte[4]; LittleEndian.PutUInt(blockKey, 0, block); MessageDigest hashAlg = CryptoFunctions.GetMessageDigest(hashAlgo); hashAlg.Update(skey.GetEncoded()); byte[] encKey = hashAlg.Digest(blockKey); EncryptionHeader header = builder.GetHeader(); int keyBits = header.KeySize; encKey = CryptoFunctions.GetBlock0(encKey, keyBits / 8); if (keyBits == 40) { encKey = CryptoFunctions.GetBlock0(encKey, 16); } ISecretKey key = new SecretKeySpec(encKey, skey.GetAlgorithm()); if (cipher == null) { cipher = CryptoFunctions.GetCipher(key, header.CipherAlgorithm, null, null, encryptMode); } else { cipher.Init(encryptMode, key); } return(cipher); }
/// <summary>A helper class to sha1 hash all the strings in a collection</summary> /// <param name="nquads"></param> /// <returns></returns> private static string Sha1hash(ICollection <string> nquads) { #if !PORTABLE try { // create SHA-1 digest MessageDigest md = MessageDigest.GetInstance("SHA-1"); foreach (string nquad in nquads) { md.Update(JsonLD.JavaCompat.GetBytesForString(nquad, "UTF-8")); } return(EncodeHex(md.Digest())); } //catch (NoSuchAlgorithmException e) //{ // throw new Exception(e); //} catch { throw; } #else throw new PlatformNotSupportedException(); #endif }
private static String Hash(string packageName, string signature) { string appInfo = packageName + " " + signature; try { MessageDigest messageDigest = MessageDigest.GetInstance(HASH_TYPE); byte[] input = Encoding.UTF8.GetBytes(appInfo); messageDigest.Update(input); byte[] hashSignature = messageDigest.Digest(); // truncated into NUM_HASHED_BYTES //hashSignature = Arrays.copyOfRange(hashSignature, 0, NUM_HASHED_BYTES); Array.Copy(hashSignature, hashSignature, NUM_HASHED_BYTES); // encode into Base64 string base64Hash = Base64.EncodeToString(hashSignature, Base64Flags.NoPadding | Base64Flags.NoWrap); base64Hash = base64Hash.Substring(0, NUM_BASE64_CHAR); Log.Debug(TAG, string.Format("pkg: %s -- hash: %s", packageName, base64Hash)); return(base64Hash); } catch (NoSuchAlgorithmException exp) { Log.Error(TAG, "hash:NoSuchAlgorithm", exp); } catch (System.Exception exp) { Log.Error(TAG, "hash:Exception", exp); } return(null); }
private string GetCurrentSignatureForPackage(string packageName) { try { PackageInfo info = Application.Context.PackageManager.GetPackageInfo(packageName, PackageInfoFlags.Signatures); #pragma warning disable CS0618 // Type or member is obsolete - https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1854 if (info != null && info.Signatures != null && info.Signatures.Count > 0) { Signature signature = info.Signatures[0]; MessageDigest md = MessageDigest.GetInstance("SHA"); md.Update(signature.ToByteArray()); return(Convert.ToBase64String(md.Digest(), Base64FormattingOptions.None)); // Server side needs to register all other tags. ADAL will // send one of them. } #pragma warning restore CS0618 // Type or member is obsolete } catch (PackageManager.NameNotFoundException) { _logger.Info("Calling App's package does not exist in PackageManager"); } catch (NoSuchAlgorithmException) { _logger.Info("Digest SHA algorithm does not exists"); } return(null); }
/// <summary>Appends data to the blob.</summary> /// <remarks>Appends data to the blob. Call this when new data is available.</remarks> public void AppendData(IEnumerable <Byte> data) { var dataVector = data.ToArray(); try { outStream.Write(dataVector); } catch (IOException e) { throw new RuntimeException("Unable to write to stream.", e); } length += dataVector.Length; sha1Digest.Update(dataVector); md5Digest.Update(dataVector); }
/// <exception cref="System.IO.IOException"></exception> private void Digest(TemporaryBuffer.Heap buf) { MessageDigest md = Constants.NewMessageDigest(); md.Update(buf.ToByteArray()); buf.Write(md.Digest()); }
private string GetCurrentSignatureForPackage(string packageName) { try { PackageInfo info = Application.Context.PackageManager.GetPackageInfo(packageName, PackageInfoFlags.Signatures); if (info != null && info.Signatures != null && info.Signatures.Count > 0) { Signature signature = info.Signatures[0]; MessageDigest md = MessageDigest.GetInstance("SHA"); md.Update(signature.ToByteArray()); return(Convert.ToBase64String(md.Digest(), Base64FormattingOptions.None)); // Server side needs to register all other tags. ADAL will // send one of them. } } catch (PackageManager.NameNotFoundException) { _logger.Info("Calling App's package does not exist in PackageManager"); } catch (NoSuchAlgorithmException) { _logger.Info("Digest SHA algorithm does not exists"); } return(null); }
public string hashCal(string type, string str) { StringBuffer hexString = new StringBuffer(); try { MessageDigest digestTxID = null; digestTxID = MessageDigest.GetInstance(type); digestTxID.Reset(); digestTxID.Update(Encoding.ASCII.GetBytes(str.ToString())); byte[] messageDigest = digestTxID.Digest(); for (int i = 0; i < messageDigest.Length; i++) { string hex = Integer.ToHexString(0xFF & messageDigest[i]); if (hex.Length == 1) { hexString.Append("0"); } hexString.Append(hex); } } catch (NoSuchAlgorithmException nsae) { } return(hexString.ToString()); }
public override void Write(byte[] buffer, int offset, int count) { _stream.Write(buffer, offset, count); _crc.Update(buffer, offset, count); _md.Update(buffer, offset, count); _count += count; }
/// <exception cref="System.IO.IOException"></exception> protected internal override void OnEndThinPack() { byte[] tailHash = this.tailDigest.Digest(); byte[] buf = Buffer(); MessageDigest origDigest = Constants.NewMessageDigest(); MessageDigest tailDigest = Constants.NewMessageDigest(); MessageDigest packDigest = Constants.NewMessageDigest(); long origRemaining = origEnd; @out.Seek(0); @out.ReadFully(buf, 0, 12); origDigest.Update(buf, 0, 12); origRemaining -= 12; NB.EncodeInt32(buf, 8, GetObjectCount()); @out.Seek(0); @out.Write(buf, 0, 12); packDigest.Update(buf, 0, 12); for (; ;) { int n = @out.Read(buf); if (n < 0) { break; } if (origRemaining != 0) { int origCnt = (int)Math.Min(n, origRemaining); origDigest.Update(buf, 0, origCnt); origRemaining -= origCnt; if (origRemaining == 0) { tailDigest.Update(buf, origCnt, n - origCnt); } } else { tailDigest.Update(buf, 0, n); } packDigest.Update(buf, 0, n); } if (!Arrays.Equals(origDigest.Digest(), origHash) || !Arrays.Equals(tailDigest.Digest (), tailHash)) { throw new IOException(JGitText.Get().packCorruptedWhileWritingToFilesystem); } packHash = packDigest.Digest(); }
/// <summary>Appends data to the blob.</summary> /// <remarks>Appends data to the blob. Call this when new data is available.</remarks> public void AppendData(IEnumerable <Byte> data) { var dataVector = data.ToArray(); length += dataVector.LongLength; sha1Digest.Update(dataVector); md5Digest.Update(dataVector); try { outStream.Write(dataVector, 0, dataVector.Length); } catch (IOException e) { throw new CouchbaseLiteException("Unable to write to stream.", e) { Code = StatusCode.Exception }; } }
internal bool HashPasswordToDigest(string user, MessageDigest digest) { return(IteratePassword(user, b => { digest.Update(b); return true; })); }
internal bool HashPasswordToDigest(string user, MessageDigest digest) { return IteratePassword(user, b => { digest.Update(b); return true; }); }