V8 JavaScript Engine 入门指南 3 -- 一个简单的V8应用

编译通过了之前的hello world程序之后,忍不住想实际运用一下V8,V8 JavaScript Engine 做为一款强大的JavaScript解析引擎,到底能为我们提供什么样的功能呢?
再来仔细看一下hello world程序:

    ......
    // Create a string containing the JavaScript source code.
    Handle<String> source = String::New("'Hello' + ', World!'");

    // Compile the source code.
    Handle<Script> script = Script::Compile(source);

    // Run the script to get the result.
    Handle<Value> result = script->Run();
    
    // Convert the result to an ASCII string and print it.
    String::AsciiValue ascii(result);
    printf("%s/n", *ascii);
    return 0;

注释解释的非常清楚:使用String::New生成源代码,使用Script::Compile编译源代码,script->Run()执行脚本得到结果
而且可以将脚本执行结果转化成ASCII字符串。并且String::New接受一个ASCII字符串作为参数。

所以,尽管我们现在对于V8的一些基本概念都不了解,但只要稍微改造一下这个hello world程序就可以实现一个简单的JavaScript解密程序!

一个简单的JavaScript解密程序功能:将加密的JavaScript代码拷贝到input.txt文件中,解密结果生成到output.txt文件中

关键代码:

/************************************************************************/
/*函数名:V8_Decryt
/*功  能:得到一段JavaScript代码的执行结果,可以用来解密JavaScript
/*返回值:结果字符串的字符数
/*注  意:返回字符串pResult的内存由调用者清理
/************************************************************************/

unsigned int V8_Decryt(const char* pExpression, //包含JavaScript代码的字符串
                                           char* &pResult          //输出参数,返回包含JavaScript代码执行结果的字符串
                                      )
{

    // Create a stack-allocated handle scope.
   
v8::HandleScope handle_scope;

    // Create a new context.
   
v8::Persistent<v8::Context> context = v8::Context::New();

    // Enter the created context for compiling and
    // running the hello world script.
   
v8::Context::Scope context_scope(context);

    // Create a string containing the JavaScript source code.
   
v8::Handle<v8::String> source = v8::String::New(pExpression);
    // Compile the source code.
   
v8::Handle<v8::Script> script = v8::Script::Compile(source);

    // Run the script to get the result.
   
v8::Handle<v8::Value> result = script->Run();

    // Dispose the persistent context.
   
context.Dispose();

    // Convert the result to a two-byte string .
   
v8::String::AsciiValue ascii(result);

    // TODO: Add extra codes here
   
unsigned int size = ascii.length();
    if(size != 0)
    {
        pResult = (char*)malloc(size+1);
        memset(pResult,0,size+1);
        memcpy_s(pResult,size,*ascii,size);
    }
    return size;
}

测试例子:

看一段eval加密

 

将eval去掉,拷贝到input.txt中去(记住保留左右括号啊),运行,查看output.txt

 

解密成功!

附上完整代码(vs2010的,就只有一个.cpp你可以方便转化到自己的vs版本)

http://download.csdn.net/source/2718386

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值