ASP.NET 서명(signature)을 생성 샘플코드
소스의 00112233445566778899aabbccddeeff 는 발급받은 32자리 키 라고 가정합니다.
예제1
<%@Import Namespace="System.Security.Cryptography" %>
<img src="http://mqr.kr/qr/?t=HelloWorld&r=10&sign=<%=CalculateSign("t=HelloWorld&r=10", "00112233445566778899aabbccddeeff")%>"/>
<script runat="server">
string CalculateSign(string text, string key)
{
byte[] keyBytes = new byte[key.Length / 2];
for (int i = 0; i < keyBytes.Length; i++)
keyBytes[i] = Convert.ToByte(key.Substring(i * 2, 2), 16);
byte[] textBytes = Encoding.ASCII.GetBytes(text);
byte[] sign;
using (HMACSHA256 hmac = new HMACSHA256(keyBytes))
sign = hmac.ComputeHash(textBytes);
return string.Join(string.Empty, sign.Select(b => b.ToString("x2")));
}
</script>
예제2
- 현재 날짜 / 시간으로 QR 코드를 생성을위한 .Net 코드 샘플
<%@Import Namespace="System.Security.Cryptography" %>
<%
string text = DateTime.Now.ToString(@"yyyy\.MM\.dd HH\:mm\:ss");
string query = string.Format("t={0}&r=10&j=1",
HttpUtility.HtmlEncode(text));
%>
<img src="http://mqr.kr/qr/?<%:query%>&sign=<%:CalculateSign(query, "00112233445566778899aabbccddeeff")%>"/>
<script runat="server">
string CalculateSign(string text, string key)
{
byte[] keyBytes = new byte[key.Length / 2];
for (int i = 0; i < keyBytes.Length; i++)
keyBytes[i] = Convert.ToByte(key.Substring(i * 2, 2), 16);
byte[] textBytes = Encoding.ASCII.GetBytes(text);
byte[] sign;
using (HMACSHA256 hmac = new HMACSHA256(keyBytes))
sign = hmac.ComputeHash(textBytes);
return string.Join(string.Empty, sign.Select(b => b.ToString("x2")));
}
</script>
예제3
- 홈페이지 현재 URL 정보를 담은 QR코드 자동 생성을위한 .Net 코드 샘플
<%@Import Namespace="System.Security.Cryptography" %>
<%
string text = Request.Url.ToString();
string query = string.Format("t={0}&r=10&j=1",
HttpUtility.HtmlEncode(text));
%>
<img src="http://mqr.kr/qr/?<%:query%>&sign=<%:CalculateSign(query, "00112233445566778899aabbccddeeff")%>"/>
<script runat="server">
string CalculateSign(string text, string key)
{
byte[] keyBytes = new byte[key.Length / 2];
for (int i = 0; i < keyBytes.Length; i++)
keyBytes[i] = Convert.ToByte(key.Substring(i * 2, 2), 16);
byte[] textBytes = Encoding.ASCII.GetBytes(text);
byte[] sign;
using (HMACSHA256 hmac = new HMACSHA256(keyBytes))
sign = hmac.ComputeHash(textBytes);
return string.Join(string.Empty, sign.Select(b => b.ToString("x2")));
}
</script>