<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Серый форум &mdash; VBS: Обфускатор/деобфускатор VBScript]]></title>
	<link rel="self" href="http://forum.script-coding.com/extern.php?action=feed&amp;tid=15789&amp;type=atom" />
	<updated>2020-11-23T23:03:58Z</updated>
	<generator>PunBB</generator>
	<id>http://forum.script-coding.com/viewtopic.php?id=15789</id>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Обфускатор/деобфускатор VBScript]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=143638#p143638" />
			<content type="html"><![CDATA[<p>Случайно наткнулся. Может тоже пригодится - <a href="https://github.com/mgeeky/VisualBasicObfuscator">https://github.com/mgeeky/VisualBasicObfuscator</a></p>]]></content>
			<author>
				<name><![CDATA[Xameleon]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=8836</uri>
			</author>
			<updated>2020-11-23T23:03:58Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=143638#p143638</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Обфускатор/деобфускатор VBScript]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=143579#p143579" />
			<content type="html"><![CDATA[<p>Глянул повнимательнее на этот проект: <a href="https://github.com/noraj/vbsmin">https://github.com/noraj/vbsmin</a>. Ребята написали неплохой &quot;уменьшитель&quot; VBScript, но на Ruby. Видимо есть у них такая необходимость.</p><p>Я не знаю Ruby, но там и так все понятно:<br />-- переписал на VBScript (лицензия MIT вроде бы позволяет), почти в лоб, пока с очень минимальной отпимизацией под язык<br />-- выкинул некоторые методы, сделал на публичных функциях, не стал оформлять в класс (потому как черновик только)<br />-- намеренно оставил все комментарии (с небольшими правками)<br />-- убрал избыточнные телодвижения с вводом/выводом - это дело вызывающей программы, а не модуля</p><p>Прогнал несколько раз свой модуль:<br />0. контрольный прогон через ruby 2.6.4p104 (2019-08-28 revision 67798) [x86_64-cygwin]</p><p>1.1. &quot;уменьшил&quot; исходный код модуля своим модулем<br />1.2. &quot;уменьшенную&quot; версию прогнал еще раз<br />Ожидаемый результаты: версии 1.1 и 1.2 совпадат с версией 0</p><p>2.1. &quot;уменьшил&quot; исходный код модуля уменьшенной весрией<br />2.2. &quot;уменьшенную&quot; версию прогнал еще раз<br />Ожидаемый результаты: &quot;уменьшенная&quot; версия работает; версии 2.1 и 2.2 совпадат с версией 0</p><div class="codebox"><pre><code>
&#039; Minify a VBScript input (make a minified copy)
&#039;
&#039; @param  [String] original VBScript text
&#039; @return [String] minified VBScript text
Function minify(text)
	Dim lines, i, line, result

	result = &quot;&quot;

	&#039; Parse the entire text as separate lines
	lines = Split(text, Chr(10))

	For i = 0 To UBound(lines)
		line = lines(i)
		line = minify_line(line)
		If line &lt;&gt; &quot;&quot; Then
			result = result &amp; line
		End If
	Next

	&#039; Remove trailing &quot;:&quot;, if any
	If Right(result, 1) = &quot;:&quot; Then
		result = Left(result, Len(result) - 1)
	End If

	minify = result
End Function

Function minify_line(line)
	Dim eol

	&#039;  End of file char
	eol = &quot;:&quot;

	&#039; Remove inline comment (must be before whitespace striping)
	line = inline_comment(line)

	&#039; Remove leading and trailing whitespaces: null, horizontal tab, line feed,
	&#039; vertical tab, form feed, carriage return, space
	line = strip(line)

	&#039; Remove comments except inline ones (must be after whitespace striping)
	If Mid(line, 1, 1) = &quot;&#039;&quot; Or UCase(Mid(line, 1, 3)) = &quot;REM&quot; Then
		line = &quot;&quot;
	End If

	&#039; Remove space when several spaces between two keywords
	line = internal_space(line)

	&#039; Remove line splitting
	If Right(line, 2) = &quot; _&quot; Then
		line = Left(line, Len(line) - 1)
		eol = &quot;&quot;
	End If

	If line &lt;&gt; &quot;&quot; Then
		line = line &amp; eol
	End If

	minify_line = line
End Function

&#039; Remove inline comments
&#039; In VBS there is no single quote strings so it&#039;s safe to remove until the end
&#039; of string when ecountering a single quote.
&#039; The only case to handle if is a single quote appears in a double quote string.
Function inline_comment(line)
	Dim quotes, i, c

	&#039; For each single quote, if there is an odd number of double quote before
	&#039; we are in a string, but if there is an even number of double quote before
	&#039; we are out of a string so this is an inline comment and we can remove all
	&#039; that comes after.
	quotes = 0
	For i = 1 To Len(line)
		c = Mid(line, i, 1)
		If c = Chr(34) Then
			quotes = quotes + 1
		End If
		If c = &quot;&#039;&quot; And quotes Mod 2 = 0 Then
			inline_comment = Mid(line, 1, i - 1)
			Exit Function
		End If
	Next

	inline_comment = line
End Function

&#039; Remove all the characters supposed to be whitespaces
Function strip(line)
	Dim re

	set re = New RegExp
	re.Pattern = &quot;^[\t\r\n\f\v ]*|[\t\r\n\f\v ]*$&quot;
	re.Global = True

	strip = re.Replace(line, &quot;&quot;)
End Function

&#039; Remove extra spaces (several spaces between two keywords except in a string)
&#039; More reliable than internal_space_old which use string replacement and string
&#039; split
Function internal_space(line)
	Dim quotes, prev, i, c, result

	&#039; For each single quote, if there is an odd number of double quote before
	&#039; we are in a string, but if there is an even number of double quote before
	&#039; we are out of a string.
	quotes = 0
	prev = &quot;&quot;

	result = &quot;&quot;

	For i = 1 To Len(line)
		c = Mid(line, i, 1)
		If c = Chr(34) Then
			quotes = quotes + 1
		End If
		If Not ( prev = &quot; &quot; And c = &quot; &quot; And quotes Mod 2 = 0 ) Then
			result = result &amp; c
		End If
		prev = c
	Next

	internal_space = result
End Function

text = WScript.StdIn.ReadAll()
text = minify(text)
WScript.StdOut.Write(text)
</code></pre></div>]]></content>
			<author>
				<name><![CDATA[Rumata]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=24846</uri>
			</author>
			<updated>2020-11-20T15:14:19Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=143579#p143579</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Обфускатор/деобфускатор VBScript]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=143501#p143501" />
			<content type="html"><![CDATA[<p><strong>Rumata</strong><br />Сделал на <strong>браузерном</strong> JavaScript перевод из Single Line Style (в основе обычный парсер строковых литералов). На &quot;:&quot; в строках не реагирует, комментарии понимает. Открываем DevTools, вставляем в консоль код. </p><div class="codebox"><pre><code>
var vbs_code = `
Sub Greet():WScript.Echo&quot;Hello, world!&quot;:End Sub:Greet

Dim a, iLen, bSpace, tmpX, tmpFull

Rem sText = &quot;:&#039;test&#039;&quot;:iLen = Len(sText)

sText = &quot;:&#039;test&#039;&quot;:iLen = Len(sText)

  For a = 1 To iLen
&#039;    If a &lt;&gt; 1 Then 
&#039;        If bSpace = True Then 
&#039;            tmpX = UCase(mid(sText,a,1)) 
&#039;            bSpace = False 
&#039;        Else
&#039;        tmpX=LCase(mid(sText,a,1))
&#039;            If tmpX = &quot; &quot; Or tmpX = &quot;&#039;&quot; Then bSpace = True
&#039;        End if 
&#039;    Else
&#039;        tmpX = UCase(mid(sText,a,1))
&#039;    End if 
 
 
   tmpFull = tmpFull &amp; tmpX
  Next
  ProperCase = tmpFull
End Function`;


function getStringPos(quotesPos)
{
	var stringPos = [];
	var startString = -1;
	var stringStarted = false;

	for (var i=0; i&lt;quotesPos.length; i++)
	{

		if (stringStarted){
			if (quotesPos[i][1] % 2 == 1)
			{
				stringStarted = false;
				stringPos.push([startString, quotesPos[i][0] + quotesPos[i][1] - 1]);
				continue;
			}

			continue;
		}
		else
		{
			if (quotesPos[i][1] % 2 == 0)
			{
				stringPos.push([quotesPos[i][0], quotesPos[i][0] + quotesPos[i][1] - 1]);
				continue;

			}
			else
			{
				stringStarted = true;
				startString = quotesPos[i][0];
				continue;
			}
		}
		  		
	}

	return stringPos;
}


var lines = vbs_code.split(/\n/g); 
var lines_result = [];

for (var l=0; l&lt;lines.length; l++)
{
	let line = lines[l]; 
	let quotesPos = [];
	let stringPos = [];

	line.replace( /&quot;&quot;*/g, (m,i)=&gt;quotesPos.push([i, m.length])  );
	let strings = getStringPos(quotesPos);

	let comment_pos = -1;
	line.replace(/&#039;|\brem\b/ig, (m,i)=&gt;{ 
		if (comment_pos!=-1) return;

		if ( strings.filter(el=&gt;i&gt;el[0]&amp;&amp;i&lt;el[1]).length==0) 
		{
			comment_pos = i;
			strings = strings.filter(el=&gt;i&gt;el[1]);
		}		
	
	});

	let result = line.replace(/:/g, (m, i)=&gt;{
		if (comment_pos!=-1 &amp;&amp; i&gt;comment_pos) return m;		
		if (strings.filter(el=&gt;i&gt;el[0]&amp;&amp;i&lt;el[1]).length ) return m; else return &quot;\n&quot;;	
	});

	lines_result.push(result);
}

console.log(lines_result.join(&quot;\n&quot;));

</code></pre></div>]]></content>
			<author>
				<name><![CDATA[JSmаn]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=24434</uri>
			</author>
			<updated>2020-11-16T16:36:57Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=143501#p143501</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Обфускатор/деобфускатор VBScript]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=143497#p143497" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>andypetr пишет:</cite><blockquote><p>Речь ведь про такое?</p></blockquote></div><p>Нет. Мне не нужно шифрование, мне нужна минификация кода. Я видел этот проект и что-то похожее на него. Пример того, что я хотел бы видеть, приведен в первом сообщении. Задача не настолько важная, поэтому писать лень и хочется чего-то готового.</p>]]></content>
			<author>
				<name><![CDATA[Rumata]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=24846</uri>
			</author>
			<updated>2020-11-16T13:12:27Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=143497#p143497</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Обфускатор/деобфускатор VBScript]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=143496#p143496" />
			<content type="html"><![CDATA[<p>Привет.<br />Речь ведь про такое? <br />(проверил на маленьком примере):<br /><a href="https://github.com/DoctorLai/VBScript_Obfuscator">https://github.com/DoctorLai/VBScript_Obfuscator</a></p>]]></content>
			<author>
				<name><![CDATA[andypetr]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=40320</uri>
			</author>
			<updated>2020-11-16T12:50:09Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=143496#p143496</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Обфускатор/деобфускатор VBScript]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=143418#p143418" />
			<content type="html"><![CDATA[<p>Да. Меня интересовали именно minifier/beautifier. Клиент-сервер - это черезчур сложно для такой задачи. Тексты других языков минимифицируются и &quot;максифицируются&quot; в пределах одного скрипта (тот же JS). Но раз нет, значит нет.</p>]]></content>
			<author>
				<name><![CDATA[Rumata]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=24846</uri>
			</author>
			<updated>2020-11-10T15:03:41Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=143418#p143418</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Обфускатор/деобфускатор VBScript]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=143117#p143117" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>Rumata пишет:</cite><blockquote><p>Есть такие на VBScript или JScript?</p></blockquote></div><p>Нет, ничего подобного не видел. Видел проект <a href="https://github.com/kastner/vbscript_in_js">перевода VBS в JScript</a> (как пример работы парсера VBS на JS), но он не впечатлил. </p><p>По сути Вы показываете пример минификации кода. Это частный случай обфускации. Для обфускации рекомендуют для начала преобразовать тело скрипта в AST (abstact syntax tree). Если же говорим об уменьшении кода путем удаления переносов строк, так и заменой &quot;:&quot; на переносы, то вполне можно это решить средствами JScript. </p><p>Если бы стояла острая задача написания такого VBS Minifier, то я бы смотрел в сторону клиент-серверных решений (что будет выдавать результат сервер - это второй вопрос при наличии существующих инструментов).</p>]]></content>
			<author>
				<name><![CDATA[JSmаn]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=24434</uri>
			</author>
			<updated>2020-11-03T20:33:24Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=143117#p143117</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[VBS: Обфускатор/деобфускатор VBScript]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=143084#p143084" />
			<content type="html"><![CDATA[<p>У нас на форуме есть старая тема <a href="http://forum.script-coding.com/viewtopic.php?id=2774">WSH: обфускация и Microsoft Script Encoder</a>. Но это немного или слишком не то, что нужно, потому что там больше про кодирование.</p><p>Меня же заинтересовало наличие скриптов, реализованных именно на VBScript. Для JavaScript есть реализации на JavaScript. Для VBScript тоже есть, но на Ruby и Python. Логично же иметь такое на именно VBScript. Например, некий файл с красивыми отступами и комментариями:</p><div class="codebox"><pre><code>
&#039; Вежливая подпрограмма
Sub Greet()
    WScript.Echo &quot;Hello, world!&quot;
End Sub

&#039; Проявляем вежливость
Greet
</code></pre></div><p>А на выходе обфускатора получаем:<br /></p><div class="codebox"><pre><code>
Sub Greet():WScript.Echo&quot;Hello, world!&quot;:End Sub:Greet
</code></pre></div><p>И в обратную сторону, естественно, с потерей коментариев. </p><p>Есть такие на VBScript или JScript?</p>]]></content>
			<author>
				<name><![CDATA[Rumata]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=24846</uri>
			</author>
			<updated>2020-11-01T23:02:42Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=143084#p143084</id>
		</entry>
</feed>
