ajax_jsonp_php加密_跨域例子

服务端 php

<?php
    header("Content-Type:text/html;charset=UTF-8");
       // $string: 明文 或 密文  
       // $operation:DECODE表示解密,其它表示加密  
       // $key: 密匙  
       // $expiry:密文有效期  
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {  
       // 动态密匙长度,相同的明文会生成不同密文就是依靠动态密匙  
    $ckey_length = 4;  
      // 密匙  
    $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);  
      // 密匙a会参与加解密  
    $keya = md5(substr($key, 0, 16));  
      // 密匙b会用来做数据完整性验证  
    $keyb = md5(substr($key, 16, 16));  
      // 密匙c用于变化生成的密文  
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';  
      // 参与运算的密匙  
    $cryptkey = $keya.md5($keya.$keyc);  
    $key_length = strlen($cryptkey);  
      //明文,前10位用来保存时间戳,解密时验证数据有效性,10到26位用来保存$keyb(密匙b),解密时会通过这个密匙验证数据完整性  
      // 如果是解码的话,会从第$ckey_length位开始,因为密文前$ckey_length位保存 动态密匙,以保证解密正确  
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;  
    $string_length = strlen($string);  
    $result = '';  
    $box = range(0, 255);  
    $rndkey = array();  
        // 产生密匙簿  
    for($i = 0; $i <= 255; $i++) {  
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);  
    }  
       // 用固定的算法,打乱密匙簿,增加随机性,好像很复杂,实际上对并不会增加密文的强度  
    for($j = $i = 0; $i < 256; $i++) {  
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;  
        $tmp = $box[$i];  
        $box[$i] = $box[$j];  
        $box[$j] = $tmp;  
    }  
       // 核心加解密部分  
    for($a = $j = $i = 0; $i < $string_length; $i++) {  
        $a = ($a + 1) % 256;  
        $j = ($j + $box[$a]) % 256;  
        $tmp = $box[$a];  
        $box[$a] = $box[$j];  
        $box[$j] = $tmp;  
           // 从密匙簿得出密匙进行异或,再转成字符  
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));  
    }  
    if($operation == 'DECODE') {  
          if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)){ 
            return substr($result, 26);
        } else {
            return '';
        }
        echo "44444444";
    } else {  
   //把动态密匙保存在密文里,这也是为什么同样的明文,生产不同密文后能解密的原因 //因为加密后的密文可能是一些特殊字符,复制过程可能会丢失,所以用base64编码  
        return $keyc.str_replace('=', '', base64_encode($result));
        echo "222222";
    }  
}
$callback = isset($_REQUEST['callback']) ? trim($_REQUEST['callback']) : '';
if (isset($_REQUEST['mystr'])){
   $str = $_REQUEST['mystr'];
   if (isset($_REQUEST['mykey'])){
      $key = $_REQUEST['mykey'];
      if (isset($_REQUEST['act'])){
         $act = $_REQUEST['act'];
         //echo 'authcode.php?act=ENCODE&mystr=TTTT&mykey=222<br>';
         //echo authcode($str,$act,$key,100);
         $codeaa=authcode($str,$act,$key,100);
         echo $callback."({ret:1,msg:'ok',key:'".$key."',code:'".$codeaa."'})";
        }else{
            echo $callback."({ret:0,msg:'错误'})";
        }
    }else{
            echo $callback."({ret:0,msg:'错误'})";
        }
}else{
            echo $callback."({ret:0,msg:'错误'})";
        }
View Code

客户端 html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    <html>  
    <head>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    <title>Ajax Jsonp</title>  
    <script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script>  
    </head>  
    <script type="text/javascript">  
    $(function(){     
        $.ajax({  
            type : "GET",  
            async:false,  
            url : "http://115.236.183.115:81/php_encode/",  
            dataType : "jsonp",
            data:{
                  act:"ENCODE",
                  mykey:"222",
                  mystr:"ggg"
                  },
            jsonp: "callback",
            success : function(data){  
                $("#showcontent").text(data.code)  
            },  
            error:function(){  
                alert('失败!');  
            }  
        });   
    });  
    </script>  
    <body>  
    <div id="showcontent">加密后字符为:</div>
    <!--http://115.236.183.115:81/php_encode/?act=ENCODE&mykey=222&mystr=ggg&callback=kkkk-->
    </body>  
    </html>  
View Code

 不跨域访问 html

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>演示:PHP加密解密字符串</title>
<style>
.demo{width:520px; margin:40px auto 0 auto; min-height:250px;}
.input{padding:3px; line-height:22px; border:1px solid #ccc}
.btn{overflow: hidden;display:inline-block;*display:inline;padding:4px 20px 4px;font-size:14px;line-height:18px;*line-height:20px;color:#fff;text-align:center;vertical-align:middle;cursor:pointer;background-color:#5bb75b;border:1px solid #cccccc;border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px; margin-left:2px}
#result{margin-top:20px; line-height:26px; color:#f30; word-break:break-all}
</style>
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script>
<script>  
$(function () {
    $("#encode").click(function(){
        post('ENCODE');//加密
    });
    $("#decode").click(function(){
        post('DECODE');//解密
    });
}); 
function post(act){
    var str = $("#str").val();
    var key = $("#key").val();
    $.post("index.php?act="+act,{mystr:str,mykey:key},function(data){
        $("#result").html(data);
    });
}
</script> 
</head>
<body>
<div id="main">
   <div class="demo">
           <textarea id="str" class="input" style="width:100%; height:80px">请输入字符串</textarea>
        密钥:<input type="text" class="input" id="key" value="www.wmdfw.com">
        <input type="button" value="加密" class="btn" id="encode">  
        <input type="button" value="解密" class="btn" id="decode">
        <div id="result"></div> 
    </div>
</div>
</body>
</html>
View Code

 js加密解密

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>字符串加密</title>
<SCRIPT LANGUAGE="JavaScript">
//加密函数开始
function encrypt(str, key) {
  if(key == null || key.length <= 0) {
    alert("Please enter a password with which to encrypt the message.");
    return null;
  }
  var prand = "";
  for(var i=0; i<key.length; i++) {
    prand += key.charCodeAt(i).toString();
  }
  var sPos = Math.floor(prand.length / 5);
  var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));
  var incr = Math.ceil(key.length / 2);
  var modu = Math.pow(2, 31) - 1;
  if(mult < 2) {
    alert("Algorithm cannot find a suitable hash. Please choose a different password. \nPossible considerations are to choose a more complex or longer password.");
    return null;
  }
  var salt = Math.round(Math.random() * 1000000000) % 100000000;
  prand += salt;
  while(prand.length > 10) {
    prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
  }
  prand = (mult * prand + incr) % modu;
  var enc_chr = "";
  var enc_str = "";
  for(var i=0; i<str.length; i++) {
    enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
    if(enc_chr < 16) {
      enc_str += "0" + enc_chr.toString(16);
    } else enc_str += enc_chr.toString(16);
    prand = (mult * prand + incr) % modu;
  }
  salt = salt.toString(16);
  while(salt.length < 8)salt = "0" + salt;
  enc_str += salt;
  alert(enc_str);
document.write("加密后的字符是:");
document.write(enc_str);
document.write("<br>");
  return enc_str;

}
//加密函数结束

//解密函数开始
function decrypt(str, key) {
  if(str == null || str.length < 8) {
    alert("A salt value could not be extracted from the encrypted message because it's length is too short. The message cannot be decrypted.");
    return;
  }
  if(key == null || key.length <= 0) {
    alert("Please enter a password with which to decrypt the message.");
    return;
  }
  var prand = "";
  for(var i=0; i<key.length; i++) {
    prand += key.charCodeAt(i).toString();
  }
  var sPos = Math.floor(prand.length / 5);
  var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));
  var incr = Math.round(key.length / 2);
  var modu = Math.pow(2, 31) - 1;
  var salt = parseInt(str.substring(str.length - 8, str.length), 16);
  str = str.substring(0, str.length - 8);
  prand += salt;
  while(prand.length > 10) {
    prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
  }
  prand = (mult * prand + incr) % modu;
  var enc_chr = "";
  var enc_str = "";
  for(var i=0; i<str.length; i+=2) {
    enc_chr = parseInt(parseInt(str.substring(i, i+2), 16) ^ Math.floor((prand / modu) * 255));
    enc_str += String.fromCharCode(enc_chr);
    prand = (mult * prand + incr) % modu;
  }
  alert(enc_str);
document.write("解密后的字符是:");
document.write(enc_str);
  return enc_str;

}
//解密函数结束

/*调用方式
var key="zhouein";
document.write("你输入的key是:");
document.write(key);
document.write("<br>");
var ipt="www.wmdfw.com";
encrypt(ipt, key);
var opt="83de93d9ba993f2d939ec395ed022f163d";
decrypt(opt, key);*/
</script>
</head>
<body>

<SCRIPT LANGUAGE="JavaScript">
var key="zhouein";
document.write("你输入的key是:");
document.write(key);
document.write("<br>");
var ipt="www.wmdfw.com";
encrypt(ipt, key);

var opt="83de93d9ba993f2d939ec395ed022f163d";
decrypt(opt, key);
</script>
</body>
</html>
View Code

 

posted @ 2016-10-13 20:49  钢锅  阅读(892)  评论(0编辑  收藏  举报