 
         var oldPosition:uint = data.position;
         data.position = offset;
-        var plainIndex:uint = offset;
-
-        while (plainIndex < length)
-        {
-            _work[_count] = data[plainIndex];
+        var currentIndex:uint = offset;
+
+        var endIndex:uint = offset + length;
+        if (endIndex > data.length)
+            endIndex = data.length;
+
+        while (currentIndex < endIndex)
+        {
+            _work[_count] = data[currentIndex];
             _count++;
 
-            if (_count == _work.length || offset + length - plainIndex == 1)
+            if (_count == _work.length || endIndex - currentIndex == 1)
             {
                 encodeBlock();
                 _count = 0;

        if (length == 0)
            length = data.length;

        var plainIndex:uint = offset;

        while (plainIndex < offset + length)
        {
            _work[_count] = data.charCodeAt(plainIndex);
            _count++;

            if (_count == _work.length || offset + length - plainIndex == 1)
            {
                encodeBlock();
                _count = 0;

                _work[1] = 0;
                _work[2] = 0;
            }
            currentIndex++;
        }

        data.position = oldPosition;
