/** * Filter FTDI status bytes from buffer * @param src The source buffer (which contains status bytes) * @param dest The destination buffer to write the status bytes into (can be src) * @param totalBytesRead Number of bytes read to src * @param maxPacketSize The USB endpoint max packet size * @return The number of payload bytes */ private int FilterStatusBytes(byte[] src, byte[] dest, int totalBytesRead, int maxPacketSize) { var packetsCount = totalBytesRead / maxPacketSize + (totalBytesRead % maxPacketSize == 0 ? 0 : 1); for (var packetIdx = 0; packetIdx < packetsCount; ++packetIdx) { var count = packetIdx == packetsCount - 1 ? totalBytesRead % maxPacketSize - MODEM_STATUS_HEADER_LENGTH : maxPacketSize - MODEM_STATUS_HEADER_LENGTH; if (count > 0) { Buffer.BlockCopy(src, packetIdx * maxPacketSize + MODEM_STATUS_HEADER_LENGTH, dest, packetIdx * (maxPacketSize - MODEM_STATUS_HEADER_LENGTH), count); } } return(totalBytesRead - packetsCount * 2); }
// // This validation logic is a manual port of StrongNameIsValidPublicKey() in the desktop CLR (see clr\src\StrongName\api\StrongNameInternal.cpp) // private static bool IsValidPublicKey(byte[] publicKey) { uint publicKeyLength = (uint)(publicKey.Length); // The buffer must be at least as large as the public key structure (for compat with desktop, we actually compare with the size of the header + 4). if (publicKeyLength < SizeOfPublicKeyBlob + 4) { return(false); } // Poor man's reinterpret_cast into the PublicKeyBlob structure. uint[] publicKeyBlob = new uint[3]; Buffer.BlockCopy(publicKey, 0, publicKeyBlob, 0, (int)SizeOfPublicKeyBlob); uint sigAlgID = publicKeyBlob[0]; uint hashAlgID = publicKeyBlob[1]; uint cbPublicKey = publicKeyBlob[2]; // The buffer must be the same size as the structure header plus the trailing key data if (cbPublicKey != publicKeyLength - SizeOfPublicKeyBlob) { return(false); } // The buffer itself looks reasonable, but the public key structure needs to be validated as well // The ECMA key doesn't look like a valid key so it will fail the below checks. If we were passed that // key, then we can skip them. if (ByteArrayEquals(publicKey, EcmaKey)) { return(true); } // If a hash algorithm is specified, it must be a sensible value bool fHashAlgorithmValid = GetAlgClass(hashAlgID) == ALG_CLASS_HASH && GetAlgSid(hashAlgID) == ALG_SID_SHA1; if (hashAlgID != 0 && !fHashAlgorithmValid) { return(false); } // If a signature algorithm is specified, it must be a sensible value bool fSignatureAlgorithmValid = GetAlgClass(sigAlgID) == ALG_CLASS_SIGNATURE; if (sigAlgID != 0 && !fSignatureAlgorithmValid) { return(false); } // The key blob must indicate that it is a PUBLICKEYBLOB if (publicKey[SizeOfPublicKeyBlob] != PUBLICKEYBLOB) { return(false); } //@todo: Desktop also tries to import the public key blob using the Crypto api as further validation - not clear if there's any non-banned API to do this. return(true); }
public override int Write(byte[] src, int timeoutMillis) { var endpoint = mDevice.GetInterface(0).GetEndpoint(1); var offset = 0; while (offset < src.Length) { int writeLength; int amtWritten; lock (mWriteBufferLock) { byte[] writeBuffer; writeLength = Math.Min(src.Length - offset, mWriteBuffer.Length); if (offset == 0) { writeBuffer = src; } else { // bulkTransfer does not support offsets, make a copy. Buffer.BlockCopy(src, offset, mWriteBuffer, 0, writeLength); writeBuffer = mWriteBuffer; } amtWritten = mConnection.BulkTransfer(endpoint, writeBuffer, writeLength, timeoutMillis); } if (amtWritten <= 0) { throw new IOException( "Error writing " + writeLength + " bytes at offset " + offset + " length=" + src.Length); } Log.Debug(TAG, "Wrote amtWritten=" + amtWritten + " attempted=" + writeLength); offset += amtWritten; } return(offset); }
//convert to Task if taking time public byte[] Generate(int length) { Debug.Assert(length > 0); Debug.Assert(_key != null); Debug.Assert(_prevSeed != null); byte[] result = new byte[length]; // Creates an instance of the SymmetricKeyAlgorithmProvider class and opens the specified algorithm for use // SymmetricAlgorithmNames.AesEcb - Retrieves a string that contains "AES_ECB". SymmetricKeyAlgorithmProvider aesProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcb); // Creates a buffer from an input byte array IBuffer keyBuffer = CryptographicBuffer.CreateFromByteArray(_key); // Creates a symmetric key // https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(Windows.Security.Cryptography.Core.SymmetricKeyAlgorithmProvider.CreateSymmetricKey);k(TargetFrameworkMoniker-.NETCore,Version%3Dv5.0);k(DevLang-csharp)&rd=true // https://msdn.microsoft.com/en-us/library/windows/apps/xaml/br241541(v=win.10).aspx?appid=dev14idef1&l=en-us&k=k(windows.security.cryptography.core.symmetrickeyalgorithmprovider.createsymmetrickey)%3bk(targetframeworkmoniker-.netcore,version%3dv5.0)%3bk(devlang-csharp)&rd=true CryptographicKey cryptographicKey = aesProvider.CreateSymmetricKey(keyBuffer); int remainingLength = length; int index = 0; while (remainingLength > 0) { int chunkLength = BtleLinkTypes.ENCRYPTED_BLOCK_SIZE - _offset; chunkLength = remainingLength < chunkLength ? remainingLength : chunkLength; if (_offset == 0) { //byte[ ] initializationVector = new byte[ BtleLinkTypes.ENCRYPTED_BLOCK_SIZE ]; // Creates a buffer from an input byte array //IBuffer ivBuffer = CryptographicBuffer.CreateFromByteArray( initializationVector ); // Creates a buffer from an input byte array IBuffer seedBuffer = CryptographicBuffer.CreateFromByteArray(_prevSeed); // Encrypt the data IBuffer encryptedSeed = CryptographicEngine.Encrypt(cryptographicKey, seedBuffer, null); Debug.Assert(encryptedSeed.Length >= BtleLinkTypes.ENCRYPTED_BLOCK_SIZE); Buffer.BlockCopy(encryptedSeed.ToArray(), 0, _prevSeed, 0, BtleLinkTypes.ENCRYPTED_BLOCK_SIZE); } Buffer.BlockCopy(_prevSeed, _offset, result, index, chunkLength); index += chunkLength; remainingLength -= chunkLength; Debug.Assert(_offset + chunkLength <= BtleLinkTypes.ENCRYPTED_BLOCK_SIZE); _offset = (_offset + chunkLength) % BtleLinkTypes.ENCRYPTED_BLOCK_SIZE; } Debug.Assert(result.Length == length); return(result); }
// The seed is either the deviceSeed or the phoneSeed, 16 bytes long public EncryptedStreamGenerator(byte[] key, byte[] seed) { Debug.Assert(key != null && key.Length == BtleLinkTypes.ENCRYPTED_BLOCK_SIZE); Debug.Assert(seed != null && seed.Length == BtleLinkTypes.ENCRYPTED_BLOCK_SIZE); _key = new byte[BtleLinkTypes.ENCRYPTED_BLOCK_SIZE]; Buffer.BlockCopy(key, 0, _key, 0, BtleLinkTypes.ENCRYPTED_BLOCK_SIZE); _prevSeed = new byte[BtleLinkTypes.ENCRYPTED_BLOCK_SIZE]; Buffer.BlockCopy(seed, 0, _prevSeed, 0, BtleLinkTypes.ENCRYPTED_BLOCK_SIZE); _offset = 0; }
void OnAudioFilterRead(float[] data, int channels) { lock (_locker) if (_recording) { var buf = _freed.Count > 0 ? _freed.Dequeue() : null; if (buf == null || buf.Length != data.Length * sizeof(float)) { buf = new byte[data.Length * sizeof(float)]; } Buffer.BlockCopy(data, 0, buf, 0, buf.Length); _inuse.Enqueue(buf); } }
public IEnumerable <HunkRangeInfo> GetGitDiffFor(ITextDocument textDocument, ITextSnapshot snapshot) { string fileName = textDocument.FilePath; GitFileStatusTracker tracker = new GitFileStatusTracker(Path.GetDirectoryName(fileName)); if (!tracker.HasGitRepository || tracker.Repository.Resolve(Constants.HEAD) == null) { yield break; } GitFileStatus status = tracker.GetFileStatus(fileName); if (status == GitFileStatus.New || status == GitFileStatus.Added) { yield break; } HistogramDiff diff = new HistogramDiff(); diff.SetFallbackAlgorithm(null); string currentText = snapshot.GetText(); byte[] preamble = textDocument.Encoding.GetPreamble(); byte[] content = textDocument.Encoding.GetBytes(currentText); if (preamble.Length > 0) { byte[] completeContent = new byte[preamble.Length + content.Length]; Buffer.BlockCopy(preamble, 0, completeContent, 0, preamble.Length); Buffer.BlockCopy(content, 0, completeContent, preamble.Length, content.Length); content = completeContent; } byte[] previousContent = GetPreviousRevision(tracker, fileName); RawText b = new RawText(content); RawText a = new RawText(previousContent ?? new byte[0]); EditList edits = diff.Diff(RawTextComparator.DEFAULT, a, b); foreach (Edit edit in edits) { yield return(new HunkRangeInfo(snapshot, edit, a, b)); } }
public override int Read(byte[] dest, int timeoutMillis) { var endpoint = mDevice.GetInterface(0).GetEndpoint(0); if (ENABLE_ASYNC_READS) { int readAmt; lock (mReadBufferLock) { // mReadBuffer is only used for maximum read size. readAmt = Math.Min(dest.Length, mReadBuffer.Length); } var request = new UsbRequest(); request.Initialize(mConnection, endpoint); var buf = ByteBuffer.Wrap(dest); if (!request.Queue(buf, readAmt)) { throw new IOException("Error queueing request."); } var response = mConnection.RequestWait(); if (response == null) { throw new IOException("Null response"); } var payloadBytesRead = buf.Position() - MODEM_STATUS_HEADER_LENGTH; if (payloadBytesRead > 0) { // CJM: This differs from the Java implementation. The dest buffer was // not getting the data back. Buffer.BlockCopy(buf.ToByteArray(), 0, dest, 0, dest.Length); Log.Debug(TAG, HexDump.DumpHexString(dest, 0, Math.Min(32, dest.Length))); return(payloadBytesRead); } return(0); } int totalBytesRead; lock (mReadBufferLock) { var readAmt = Math.Min(dest.Length, mReadBuffer.Length); // todo: replace with async call totalBytesRead = mConnection.BulkTransfer(endpoint, mReadBuffer, readAmt, timeoutMillis); if (totalBytesRead < MODEM_STATUS_HEADER_LENGTH) { throw new IOException( "Expected at least " + MODEM_STATUS_HEADER_LENGTH + " bytes"); } return(FilterStatusBytes(mReadBuffer, dest, totalBytesRead, endpoint.MaxPacketSize)); } }
public override int Read(byte[] dest, int timeoutMillis) { if (mEnableAsyncReads) { var request = new UsbRequest(); try { request.Initialize(mConnection, mReadEndpoint); // CJM: Xamarin bug: ByteBuffer.Wrap is supposed to be a two way update // Changes made to one buffer should reflect in the other. It's not working // As a work around, I added a new method as an extension that uses JNI to turn // a new byte[] array. I then used BlockCopy to copy the bytes back the original array // see https://forums.xamarin.com/discussion/comment/238396/#Comment_238396 // // Old work around: // as a work around, we populate dest with a call to buf.Get() // see https://bugzilla.xamarin.com/show_bug.cgi?id=20772 // and https://bugzilla.xamarin.com/show_bug.cgi?id=31260 var buf = ByteBuffer.Wrap(dest); if (!request.Queue(buf, dest.Length)) { throw new IOException("Error queueing request."); } var response = mConnection.RequestWait(); if (response == null) { throw new IOException("Null response"); } var nread = buf.Position(); if (nread > 0) { // CJM: This differs from the Java implementation. The dest buffer was // not getting the data back. // 1st work around, no longer used //buf.Rewind(); //buf.Get(dest, 0, dest.Length); Buffer.BlockCopy(buf.ToByteArray(), 0, dest, 0, dest.Length); Log.Debug(TAG, HexDump.DumpHexString(dest, 0, Math.Min(32, dest.Length))); return(nread); } else { return(0); } } finally { request.Close(); } } int numBytesRead; lock (mReadBufferLock) { var readAmt = Math.Min(dest.Length, mReadBuffer.Length); numBytesRead = mConnection.BulkTransfer(mReadEndpoint, mReadBuffer, readAmt, timeoutMillis); if (numBytesRead < 0) { // This sucks: we get -1 on timeout, not 0 as preferred. // We *should* use UsbRequest, except it has a bug/api oversight // where there is no way to determine the number of bytes read // in response :\ -- http://b.android.com/28023 if (timeoutMillis == Integer.MaxValue) { // Hack: Special case "~infinite timeout" as an error. return(-1); } return(0); } Buffer.BlockCopy(mReadBuffer, 0, dest, 0, numBytesRead); } return(numBytesRead); }