C# AES加解密

最近常遇到需要使用AES加解密的需求,無論是網路傳輸/API相關的部份。
分享一下
Github原始碼下載
https://github.com/superlevin/CSharpAES

using System.Security.Cryptography;
public static string SHAEncrypt(string str)
{
var crypt = new System.Security.Cryptography.SHA256Managed();
var hash = new System.Text.StringBuilder();
byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(str));
foreach (byte theByte in crypto)
{
hash.Append(theByte.ToString("x2"));
// x小寫 X 大寫 x2 補0
}
return hash.ToString();
}
public static string AESEncrypt(string str, string strkey, string strivKey, bool isVasEncrypt = false)
{

var aesCipher = new AesManaged
{
KeySize = 128,
BlockSize = 128,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
};

var keyStr = KeyGenerator(strkey);
var key = Convert.FromBase64String(keyStr);
var ivKey = Encoding.UTF8.GetBytes(strivKey);
var input = str;
var ivStr = Convert.ToBase64String(ivKey);

aesCipher.Key = key;
aesCipher.IV = ivKey;
byte[] b = System.Text.Encoding.UTF8.GetBytes(str); // plain text to be encrypted
ICryptoTransform encryptTransform = aesCipher.CreateEncryptor();
byte[] cipherText = encryptTransform.TransformFinalBlock(b, 0, b.Length);
return Convert.ToBase64String(cipherText);
}
public static string AESDecrypt(string encstring, string strkey, string strivKey)
{
var aesCipher = new AesManaged
{
KeySize = 128,
BlockSize = 128,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
};
var keyStr = KeyGenerator(strkey);
var key = Convert.FromBase64String(keyStr);
aesCipher.Key = key;
aesCipher.IV = Encoding.UTF8.GetBytes(strivKey);

var encryptBytes = Convert.FromBase64String(encstring);
ICryptoTransform decryptTransform = aesCipher.CreateDecryptor();
byte[] plainText = decryptTransform.TransformFinalBlock(encryptBytes, 0, encryptBytes.Length);

return System.Text.Encoding.UTF8.GetString(plainText);
}

利用Cpanel API建立子網域

549400

因為租用虛擬主機時有cPanel後台,又因為太過於懶惰,不想進入程式設定。
幸好cPanel有提供API
下載Cpanel的XML-API.php

[php]
<?php require_once(‘./xmlapi.php’); $cpanelusr = ‘xxxx’; //您的cPanel帳號 $cpanelpass = ‘xxx’; //您的cPanel密碼 $domainroot = ‘xxxx.com.tw’; //網域名稱 $subdomain = ‘abc’; //建立的子網域名稱 $xmlapi = new xmlapi(‘localhost’); //ip or localhost $xmlapi->set_port( 2083 ); //建立port
$xmlapi->password_auth($cpanelusr,$cpanelpass);
$xmlapi->set_debug(0);
$xmlapi->api1_query($cpanelusr, ‘SubDomain’, ‘addsubdomain’, array($subdomain, $domainroot,0,0, "/public_html/{$subdomain}"));
echo ‘子網域建立成功’;
?>
[/php]

一直很喜歡它的主機服務。推給大家

遠振主機

網址:

https://host.com.tw

facebook寫自動貼文程式時access token權杖時效問題

1465550363703
在寫facebook的自動貼文或程式時,需要有access token,但access token的時效不長。該如何延長時間?
1
進入Graph API測試工具(https://developers.facebook.com/tools/explorer/)取得暫時性的權杖。
2
透過下列網址將APP_ID APP_SECRET ACCESS_TOKEN置換成對應的值

https://graph.facebook.com/oauth/access_token? client_id={APP_ID}& client_secret={APP_SECRET}& fb_exchange_token={SHORTLIVED_ACCESS_TOKEN}& grant_type=fb_exchange_token

3
如果還不行,可以利用Access Token Debugger工具(https://developers.facebook.com/tools/debug/access_token/),將暫時性的權杖輸入後,也可以取得長效(60天)的token。
那如何驗證過期與否重取得??官方給了做法
[php]
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_POST_LOGIN_URL";

// known valid access token stored in a database
$access_token = "YOUR_STORED_ACCESS_TOKEN";

$code = $_REQUEST["code"];

// If we get a code, it means that we have re-authed the user
//and can get a valid access_token.
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params[‘access_token’];
}

// Attempt to query the graph:
$graph_url = "https://graph.facebook.com/me?"
. "access_token=" . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);

//Check for errors
if ($decoded_response->error) {
// check to see if this is an oAuth error:
if ($decoded_response->error->type== "OAuthException") {
// Retrieving a valid access token.
$dialog_url= "https://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($my_url);
echo("<script> top.location.href=’" . $dialog_url
. "'</script>");
}
else {
echo "other error has happened";
}
}
else {
// success
echo("success" . $decoded_response->name);
echo($access_token);
}

// note this wrapper function exists in order to circumvent PHP’s
//strict obeying of HTTP error codes. In this case, Facebook
//returns error code 400 which PHP obeys and wipes out
//the response.
function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
?>
[/php]

參考:
https://developers.facebook.com/blog/post/2011/05/13/how-to–handle-expired-access-tokens/

Google Map panto試做

[javascript]
function Move2NextMarker1(){
var marker=markers1[tempMarker1];
map.panTo(markers1[tempMarker1].getPosition());
scontent = ‘<div id="iw-container">’ +
‘<div class="iw-title">’+markers[tempMarker1].title+'</div>’ +
‘<div class="iw-content">’ +markers[tempMarker1].description+
‘</div>’ +
‘<div class="iw-bottom-gradient"></div>’ +
‘</div>’;
infoWindow.setContent(scontent);
infoWindow.open(map,markers1[tempMarker1]);
setTimeout(Move2NextMarker1,5600);
tempMarker1=(tempMarker1+1)%(markers.length);

}
[/javascript]

PHP透過curl上傳xml給API

[php]

<?php
$xml_data ='<?xml version="1.0" encoding="UTF-8"?>
<FILE>
<HEAD>
<FILEDESC>ORDER</FILEDESC>
</HEAD>
<CONTENT>
<DATA>
<ID>XXXX</ID>
<MEMO>XXXXXXX</MEMO>
</DATA>
</CONTENT>
</FILE>
‘;

$URL = "http://apisite";

$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_MUTE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(‘Content-Type: text/xml’));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
[/php]