语言包含:
Javascript ,PHP,Java,Groovy,C#,Objective C,Go,Ruby,Python,Perl,Dart,Swift,Rust,Powershell。 Javascript HMAC SHA256 Run the code online with this jsfiddle. Dependent upon an open source js library calledhttp://code.google.com/p/crypto-js/. <script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha256.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js"></script> <script>
var hash = CryptoJS.HmacSHA256("Message", "secret");
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
document.write(hashInBase64);
</script>
PHP HMAC SHA256 PHP has built in methods for hash_hmac (PHP ) and base64_encode (PHP , PHP ) resulting in no outside dependencies. Say what you want about PHP but they have the cleanest code for this example. $s = hash_hmac('sha256', 'Message', 'secret', true);
echo base64_encode($s);
Java HMAC SHA256 Dependent on Apache Commons Codec to encode in base64. import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64; public class ApiSecurityExample {
public static void main(String[] args) {
try {
String secret = "secret";
String message = "Message"; Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key); String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
System.out.println(hash);
}
catch (Exception e){
System.out.println("Error");
}
}
}
Groovy HMAC SHA256 It is mostly Java code but there are some slight differences. Adapted from Dev Takeout - Groovy HMAC/SHA256 representation. import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException; def hmac_sha256(String secretKey, String data) {
try {
Mac mac = Mac.getInstance("HmacSHA256")
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256")
mac.init(secretKeySpec)
byte[] digest = mac.doFinal(data.getBytes())
return digest
} catch (InvalidKeyException e) {
throw new RuntimeException("Invalid key exception while converting to HMac SHA256")
}
} def hash = hmac_sha256("secret", "Message")
encodedData = hash.encodeBase64().toString()
log.info(encodedData)
C# HMAC SHA256 using System.Security.Cryptography; namespace Test
{
public class MyHmac
{
private string CreateToken(string message, string secret)
{
secret = secret ?? "";
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(secret);
byte[] messageBytes = encoding.GetBytes(message);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return Convert.ToBase64String(hashmessage);
}
}
}
}
Objective C and Cocoa HMAC SHA256 Most of the code required was for converting to bae64 and working the NSString and NSData data types. #import "AppDelegate.h"
#import <CommonCrypto/CommonHMAC.h> @implementation AppDelegate - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSString* key = @"secret";
NSString* data = @"Message"; const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *hash = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)]; NSLog(@"%@", hash); NSString* s = [AppDelegate base64forData:hash];
NSLog(s);
} + (NSString*)base64forData:(NSData*)theData {
const uint8_t* input = (const uint8_t*)[theData bytes];
NSInteger length = [theData length]; static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; NSMutableData* data = [NSMutableData dataWithLength:((length + ) / ) * ];
uint8_t* output = (uint8_t*)data.mutableBytes; NSInteger i;
for (i=; i < length; i += ) {
NSInteger value = ;
NSInteger j;
for (j = i; j < (i + ); j++) {
value <<= ; if (j < length) { value |= (0xFF & input[j]); } } NSInteger theIndex = (i / ) * ; output[theIndex + ] = table[(value >> ) & 0x3F];
output[theIndex + ] = table[(value >> ) & 0x3F];
output[theIndex + ] = (i + ) < length ? table[(value >> ) & 0x3F] : '=';
output[theIndex + ] = (i + ) < length ? table[(value >> ) & 0x3F] : '=';
} return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; } @end
Go programming language - Golang HMAC SHA256 Try it online in your browser with Play GoLang
crypto/hmac package
package main import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
) func ComputeHmac256(message string, secret string) string {
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write([]byte(message))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
} func main() {
fmt.Println(ComputeHmac256("Message", "secret"))
}
Ruby HMAC SHA256 Requires openssl and base64. require 'openssl'
require "base64" hash = OpenSSL::HMAC.digest('sha256', "secret", "Message")
puts Base64.encode64(hash)
Python (2.7) HMAC SHA256 import hashlib
import hmac
import base64 message = bytes("Message").encode('utf-8')
secret = bytes("secret").encode('utf-8') signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest())
print(signature)
Tested with Python 2.7.. Also, be sure not to name your python demo script the same as one of the imported libraries. Perl HMAC SHA256 See Digest::SHA documentation. By convention, the Digest modules do not pad their Base64 output. To fix this you can test the length of the hash and append equal signs "=" until it is the length is a multiple of . We will use a modulus function below. use Digest::SHA qw(hmac_sha256_base64);
$digest = hmac_sha256_base64("Message", "secret"); # digest is currently: qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc # Fix padding of Base64 digests
while (length($digest) % ) {
$digest .= '=';
} print $digest;
# digest is now: qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=
Dart HMAC SHA256 Dependent upon the Dart crypto package. import 'dart:html';
import 'dart:convert';
import 'package:crypto/crypto.dart'; void main() { String secret = 'secret';
String message = 'Message'; List<int> secretBytes = UTF8.encode('secret');
List<int> messageBytes = UTF8.encode('Message'); var hmac = new HMAC(new SHA256(), secretBytes);
hmac.add(messageBytes);
var digest = hmac.close(); var hash = CryptoUtils.bytesToBase64(digest); // output to html page
querySelector('#hash').text = hash;
// hash => qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=
}
Swift HMAC SHA256 I have not verified but see this stackOverflow post Rust Take a look at the alco/rust-digest repository for Rust (lang) guidance. I have not verified yet. Powershell (Windows) HMAC SHA256 Mostly wrapping of .NET libraries but useful to see it in powershell's befuddling syntax. See code as gist $message = 'Message'
$secret = 'secret' $hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Text.Encoding]::ASCII.GetBytes($secret)
$signature = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($message))
$signature = [Convert]::ToBase64String($signature) echo $signature # Do we get the expected signature?
echo ($signature -eq 'qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=')

原文

各种语言HMAC SHA256实现的更多相关文章

  1. C#(.NET) HMAC SHA256实现

    HMAC SHA256的实现比较简单,可以用多种语言实现,下面我用C#语言实现,一种结果是居于BASE64,另外一种是居于64位. C# HMAC SHA256 (Base64) using Syst ...

  2. 密码学奇妙之旅、03 HMAC单向散列消息认证码、Golang代码

    HMAC 单向散列消息认证码 消息认证码MAC是用于确认完整性并进行认证的技术,消息认证码的输入包括任意长度的消息和一个发送者和接收者之间共享的密钥(可能还需要共享盐值). HMAC是使用单向散列函数 ...

  3. YbSoftwareFactory 代码生成插件【十三】:Web API 的安全性

    ASP.NET Web API 可非常方便地创建基于 HTTP 的 Services,这些服务可以非常方便地被几乎任何形式的平台和客户端(如浏览器.Windows客户端.Android设备.IOS等) ...

  4. iOS - Safe iOS 加密安全

    1.Base64 编码 简介: Base64 是一种基于64个可打印字符来表示二进制数据的表示方法,可打印字符包括字母 A-Z.a-z.0-9,共 62 个字符,另外两个符号在不同的系统不同 +,/. ...

  5. 转:RTMPDump源代码分析

    0: 主要函数调用分析 rtmpdump 是一个用来处理 RTMP 流媒体的开源工具包,支持 rtmp://, rtmpt://, rtmpe://, rtmpte://, and rtmps://. ...

  6. OpenID说明

    OpenID使用手册 摘要: OpenID是一种开放.离散式的用于用户数字标识的开源框架.在网络应用日益充斥的今天,作为终端用户的我们不得不在每个网站上设置帐号,并管理众多的帐号.而采用OpenID技 ...

  7. Web API 的安全性

    Web API 的安全性 ASP.NET Web API 可非常方便地创建基于 HTTP 的 Services,这些服务可以非常方便地被几乎任何形式的平台和客户端(如浏览器.Windows客户端.An ...

  8. ASP.NET Core 认证与授权[4]:JwtBearer认证

    在现代Web应用程序中,通常会使用Web, WebApp, NativeApp等多种呈现方式,而后端也由以前的Razor渲染HTML,转变为Stateless的RESTFulAPI,因此,我们需要一种 ...

  9. JSON Web Tokens(JWT)

    现在API越来越流行,如何安全保护这些API? JSON Web Tokens(JWT)能提供基于JSON格式的安全认证.它有以下特点: JWT是跨不同语言的,JWT可以在 .NET, Python, ...

随机推荐

  1. poj 2778 DNA Sequence AC自动机DP 矩阵优化

    DNA Sequence Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 11860   Accepted: 4527 Des ...

  2. java中的日期格式

    时间日期标识符: yyyy:年 MM:月 dd:日 hh:~12小时制(-) HH:24小时制(-) mm:分 ss:秒 S:毫秒 E:星期几 D:一年中的第几天 F:一月中的第几个星期(会把这个月总 ...

  3. QT5.1.1中MinGW4.8的环境变量配置

    1.右击“我的电脑”图标,在弹出的菜单上选择“属性(R)”菜单项. 2.选择“高级”选项卡.点击“环境变量”按钮. 3.点击“新建(W)”按钮,新建环境变量:MINGW_HOME,变量值为MinGW的 ...

  4. 加快AndroidStudio运行速度的方法

    之前用过其他人加速AndroidStudio构建速度的方法,确实在编译时有一定的效果 但是在实际使用中,随着项目越来越大,AndroidStudio有时还是会卡死,或者直接黑屏,我的笔记本是8g内存 ...

  5. Android 自定义dialog(AlertDialog的修改样式)

    LayoutInflater inflater = LayoutInflater(AudioActivity.this); View timepickerview = inflater.inflate ...

  6. 【转】MFC窗口句柄各类指针获取函数

    原文网址:http://www.pythonschool.com/CPP_JHK/5003.html 获取所在类窗口的句柄 this->m_hwnd; // this是一个指针,指向当前类的实例 ...

  7. QTP自动化测试权威指南 连载(一)

    第一章 简介 什么是自动化测试 自动化测试是对一个已有的手工测试过程减少并尽可能排除人工干预的过程. 什么时候适合做自动化测试 下面是一组适合将手工测试自动化的考量因素: ● 测试需要经常重复. ● ...

  8. Qt 与 JavaScript 通信

    使用QWebView加载网页后,解决Qt与JavaScript通信的问题: The QtWebKit Bridge :http://qt-project.org/doc/qt-4.8/qtwebkit ...

  9. Supervisord管理

    原文地址:http://blog.csdn.net/fyh2003/article/details/6837970 学习笔记 Supervisord可以通过sudo easy_install supe ...

  10. Myeclipse在启动Tomcat服务器的时候总是进入debug视图的解决方法

    最近调试程序,由于出现过一些错误,在调试的时候,更改过一些东西,但是后来在myeclipse下启动Tomcat服务器的时候,自动的跳入到debug视图了(以前是一启动Tomcat服务器后,直接就加载t ...