码迷,mamicode.com
首页 > 其他好文 > 详细

发送加密短信参考

时间:2016-07-03 00:35:43      阅读:423      评论:0      收藏:0      [点我收藏+]

标签:

C#代码示例

http请求
string url="http://xxx.com/api/MsgSend.asmx";

        protected string sendmsgencryptByPost() //POST方式请求
        {
            string encryptCode=EncodeStr("userPass=密码&DesNo=手机号&Msg=短信内容【签名】&Channel=通道号",SHA1_Hash(密码));
            StringBuilder sb = new StringBuilder();
            sb.Append("userCode=用户名&");
            sb.Append("submitInfo="+encryptCode);
            string result = httpPost(url + "/sendMsgByEncrypt", sb.ToString());

            return result;
        }

        protected string sendmsgencryptByGet() //Get方式请求
        {
            string encryptCode=EncodeStr("userPass=密码&DesNo=手机号&Msg=短信内容【签名】&Channel=通道号",SHA1_Hash(密码));
            StringBuilder sb = new StringBuilder();
            sb.Append("userCode=用户名&");
            sb.Append("submitInfo="+encryptCode);
            string result = httpGet(url + "/sendMsgByEncrypt", sb.ToString());
            return result;
        }

        protected string httpGet(string url, string data) //http get请求
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + data);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                return retString;
            }
            catch (Exception ex)
            {

                return ex.Message;
            }
        }
        protected string httpPost(string url, string data) //http post请求
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                byte[] info = Encoding.UTF8.GetBytes(data);
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(info, 0, info.Length);
                }
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                return retString;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public string EncodeStr(string str, string key) //DES加密
        {
            try
            {
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
                provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
                byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(str);
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
                stream2.Write(bytes, 0, bytes.Length);
                stream2.FlushFinalBlock();
                StringBuilder builder = new StringBuilder();
                foreach (byte num in stream.ToArray())
                {
                    builder.AppendFormat("{0:X2}", num);
                }
                stream.Close();
                return builder.ToString();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public string SHA1_Hash(string str_sha1_in) //sha1加密
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] bytes_sha1_in = UTF8Encoding.Default.GetBytes(str_sha1_in);
            byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);
            string str_sha1_out = BitConverter.ToString(bytes_sha1_out);
            str_sha1_out = str_sha1_out.Replace("-", "");
            return str_sha1_out;
        }

   

例如:需加密的字符串拼接后为:
userPass=123
加密过程如下:
密码是:123,先将密码123进行SHA1加密,值为:40BD001563085FC35165329EA1FF5C5ECBDBBEEF
取密码SHA1加密之后前8位:40BD0015。
对需加密的字符串进行DES加密其中key和IV都设置为:40BD0015
得到结果为:9ECD998D9F60F7965346EF832F706FD7
最后加密结果即作为接口请求时的submitInfo参数


webservice请求

       private void SendMsgByEncrypt()
        {
            TopenServiceReference.MsgSendSoapClient topen = new TopenServiceReference.MsgSendSoapClient();
            string userName = "用户名";
            string encryptCode=EncodeStr("userPass=密码&DesNo=手机号&Msg=短信内容【签名】&Channel=通道号",SHA1_Hash(密码));
            string sendResult = topen.sendMsgByEncrypt(userName, encryptCode);

            //然后,根据返回的sendResult作相应处理
        }

 

 PHP代码示例

http请求

<?php

$urlsend="http://xxx.com/api/MsgSend.asmx/sendMsgByEncrypt";

$key=substr(sha1("密码"),0,8);

$str="userCode=密码&DesNo=手机号&Msg=短信内容【签名】&Channel=通道号";

$encryptstr=iconv("GBK","GB2312",$str);

$encryptCode=encrypt($encryptstr,$key,$key);

$token=array("userCode"=>"用户名","submitInfo"=>$encryptCode);

echo http($urlsend,$token,"GET"); //get请求

echo http($urlsend,$token,"POST"); //post请求

    function encrypt($str,$key,$iv) {
    //加密,返回大写十六进制字符串
        $size = mcrypt_get_block_size ( MCRYPT_DES, MCRYPT_MODE_CBC );
        $str = pkcs5Pad ( $str, $size );
        return strtoupper( bin2hex( mcrypt_cbc(MCRYPT_DES, $key, $str, MCRYPT_ENCRYPT, $iv ) ) );
    }
    
    function decrypt($str,$key,$iv) {
    //解密
        $strBin = $this->hex2bin( strtolower( $str ) );
        $str = mcrypt_cbc( MCRYPT_DES, $key, $strBin, MCRYPT_DECRYPT, $iv );
        $str = $this->pkcs5Unpad( $str );
        return $str;
    }
    
    function hex2bin($hexData) {
        $binData = "";
        for($i = 0; $i < strlen ( $hexData ); $i += 2) {
            $binData .= chr ( hexdec ( substr ( $hexData, $i, 2 ) ) );
        }
        return $binData;
    }

    function pkcs5Pad($text, $blocksize) {
        $pad = $blocksize - (strlen ( $text ) % $blocksize);
        return $text . str_repeat ( chr ( $pad ), $pad );
    }
    
    function pkcs5Unpad($text) {
        $pad = ord ( $text {strlen ( $text ) - 1} );
        if ($pad > strlen ( $text ))
            return false;
        if (strspn ( $text, chr ( $pad ), strlen ( $text ) - $pad ) != $pad)
            return false;
        return substr ( $text, 0, - 1 * $pad );
    }

function http($url,$param,$action="GET"){
    $ch=curl_init();
    $config=array(CURLOPT_RETURNTRANSFER=>true,CURLOPT_URL=>$url);    
    if($action=="POST"){
        $config[CURLOPT_POST]=true;        
    }
    $config[CURLOPT_POSTFIELDS]=http_build_query($param);
    curl_setopt_array($ch,$config);    
    $result=curl_exec($ch);    
    curl_close($ch);
    return $result;
}
?>

 

webservice请求

<?php
    //此处仅示例发送短信,其他可类推
    header("Content-type: text/html; charset=utf-8");
    $client = new SoapClient("http://xxxx.com/api/MsgSend.asmx?WSDL");

    $key=substr(sha1("密码"),0,8);

    $str="userCode=密码&DesNo=手机号&Msg=短信内容【签名】&Channel=通道号";

    $encryptstr=iconv("GBK","GB2312",$str);

    $encryptCode=encrypt($encryptstr,$key,$key);

    $param=array("userCode"=>"用户名","submitInfo"=>$encryptCode);

    $p = $client->sendMsgByEncrypt($param);
    print_r($p);
    ?>

 

java代码示例


http请求

        //说明:此处需引用httpclient、httpcore、commons-logging三个jar包

        import java.io.BufferedReader;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.util.*;
        import java.security.MessageDigest;
        import org.apache.http.HttpEntity;
        import org.apache.http.HttpResponse;
        import org.apache.http.client.HttpClient;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.client.methods.HttpGet;
        import org.apache.http.client.entity.UrlEncodedFormEntity;
        import org.apache.http.impl.client.DefaultHttpClient;
        import org.apache.http.message.BasicNameValuePair;
        import org.apache.http.*;
        import javax.crypto.SecretKey;
        import javax.crypto.spec.DESKeySpec;
        import javax.crypto.spec.IvParameterSpec;
        import javax.crypto.SecretKeyFactory;
        import javax.crypto.Cipher;

        public static void main(String[] args) {
            String url="http://xxxx.com/api/MsgSend.asmx/sendMsgByEncrypt";

            String encryptStr=DESEncrypt("userPass=密码&DesNo=手机号&Msg=短信内容【签名】&Channel=通道号","密码");

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("userCode", "用户名"));
            nvps.add(new BasicNameValuePair("submitInfo",encryptStr));


            String post=httpPost(url,nvps);  //post请求

            String getparam="userCode=用户名&submitInfo="+encryptStr;
            String result=httpGet(url,getparam); //get请求
        }

        public static String DESEncrypt(String encryptStr,String key){        
        String result="";
        try
        {
            String encryptKey=SHA1(key).substring(0, 8).toUpperCase();;
            DESKeySpec desKeySpec=new DESKeySpec(encryptKey.getBytes());
            SecretKeyFactory keyFactory=SecretKeyFactory.getInstance("DES");
            SecretKey securekey=keyFactory.generateSecret(desKeySpec);
            Cipher cipher=Cipher.getInstance("DES/CBC/PKCS5Padding");
            IvParameterSpec ivp=new IvParameterSpec(encryptKey.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE,securekey,ivp);
            byte[] encryptResult=cipher.doFinal(encryptStr.getBytes("GB2312"));
            result=BinaryToHexString(encryptResult);
        }
        catch(Exception e){
            System.out.println(e.getStackTrace());
            System.out.println(e.getMessage());
        }      
        return result;
    }    
    
    public static String SHA1(String key){
        StringBuffer sb=new StringBuffer();
        try{
            MessageDigest md=MessageDigest.getInstance("SHA-1");
            md.update(key.getBytes("GB2312"));
            byte[] resultsha=md.digest();            
            for(byte b:resultsha){
                int i = b & 0xff;
                if (i < 0xf) {
                    sb.append(0);
                }
                sb.append(Integer.toHexString(i));
            }            
        }catch(Exception e){}     
        return sb.toString();
    }
    
    public static String BinaryToHexString(byte[] bytes){
        String hexStr =  "0123456789ABCDEF";
        String result = "";
        String hex = "";  
        for(int i=0;i<bytes.length;i++){
            //字节高4位  
            hex = String.valueOf(hexStr.charAt((bytes[i]&0xF0)>>4));
            //字节低4位  
            hex += String.valueOf(hexStr.charAt(bytes[i]&0x0F));  
            result +=hex;  
        }
        return result;  
    }

    public static String httpPost(String url,List<NameValuePair> params) {
            String result = "";
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);            
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {    
                 InputStream instreams = entity.getContent();    
                 result = convertStreamToString(instreams);  
                 System.out.println(result);  
             }
        } catch (Exception e) {
        }
        return result;
    }
    
    public static String httpGet(String url,String params){
        String result="";        
        try{
            HttpClient client=new DefaultHttpClient();            
            if(params!=""){
                url=url+"?"+params;
            }            
            HttpGet httpget=new HttpGet(url);
            HttpResponse response=client.execute(httpget);            
            HttpEntity entity=response.getEntity();
            if (entity != null) {    
                 InputStream instreams = entity.getContent();    
                 result = convertStreamToString(instreams);  
                 System.out.println(result);  
             }
        }catch(Exception e){}
        return result;
    }
    
    public static String convertStreamToString(InputStream is) {      
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));      
        StringBuilder sb = new StringBuilder();      
       
        String line = null;
        try {      
            while ((line = reader.readLine()) != null) {  
                sb.append(line + "\n");      
            }      
        } catch (IOException e) {      
            e.printStackTrace();      
        } finally {
            try {
                is.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
        }
        return sb.toString();
    }


webservice请求

        public static void main(String[] args) {
            org.tempuri.MsgSend service = new org.tempuri.MsgSend();
            org.tempuri.MsgSendSoap port = service.getMsgSendSoap();
            String encryptStr=DESEncrypt("userPass=密码&DesNo=手机号&Msg=短信内容【签名】&Channel=通道号","密码");
            String result= port.sendMsgByEncrypt("用户名",encryptStr);
            System.out.println(result);
        }
                 

 

 asp代码示例


http请求

<!—— #include file ="DESClass.asp" ——>
<!—— #include file="sha1.js.inc" ——>
<%
dim sendurl,senddata

set des=new DesClass

encryptstr="userPass=密码&DesNo=手机号&Msg=短信内容【签名】&Channel=通道号"
encryptkey=UCase(left(hex_sha1("密码"),8))

des.Key = encryptkey
des.IV = encryptkey cbc mode only
des.Mode = "cbc"
des.Padding = "pkcs5"
des.Encoding = "GB2312"

submitInfo=UCase(des.Encode(encryptstr))

sendurl="http://xxxx.com/api/MsgSend.asmx/sendMsgByEncrypt"
senddata="userCode=用户名&submitInfo="+submitInfo

Response.Write(HTTPRequest(sendurl,senddata,"GET")) <!—— get请求 ——>

Response.Write(HTTPRequest(sendurl,senddata,"POST")) <!—— post请求 ——>

function HTTPRequest(url,data,method)
    dim http
    set http=server.createobject("MSXML2.SERVERXMLHTTP.3.0")

    if method = "GET" then
    Http.open "GET",url+"?"+data,false
    elseif method = "POST" then
    Http.open "POST",url,false
    end if

    Http.setRequestHeader "CONTENT-TYPE","application/x-www-form-urlencoded"
    Http.send(data)
    if Http.readystate<>4 then
    exit function
    End if

    HTTPRequest=BytesToStr(Http.responseBody,"utf-8")
    set http=nothing
    if err.number<>0 then err.Clear
End function

Function BytesToStr(body, charset)
    Dim objStream
    Set objStream = Server.CreateObject("Adodb.Stream")
    objStream.Type = 1
    objStream.Mode = 3
    objStream.Open
    objStream.Write body
    objStream.Position = 0
    objStream.Type = 2
    objStream.Charset = charset
    BytesToStr = objStream.ReadText
    objStream.Close
    Set objStream = Nothing
End Function

%>

 

发送加密短信参考

标签:

原文地址:http://www.cnblogs.com/hnsongbiao/p/5636369.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!