SHA256加密-各種語言版本的基於HMAC-SHA256的base64加密
語言包含:
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 5) and base64_encode (PHP 4, PHP 5) 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 + 2) / 3) * 4];
uint8_t* output = (uint8_t*)data.mutableBytes;
NSInteger i;
for (i=0; i < length; i += 3) {
NSInteger value = 0;
NSInteger j;
for (j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) { value |= (0xFF & input[j]); } } NSInteger theIndex = (i / 3) * 4; output[theIndex + 0] = table[(value >> 18) & 0x3F];
output[theIndex + 1] = table[(value >> 12) & 0x3F];
output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; }
@end
Go programming language - Golang HMAC SHA256
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
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.6. 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 4. 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) % 4) {
$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=')
摘自:http://www.jokecamp.com/blog/examples-of-creating-base64-hashes-using-hmac-sha256-in-different-languages/#java
原文地址:http://www.cnblogs.com/pengyingh/articles/2501292.html
--------------------------------------
PS: PKCS5_PBKDF2_HMAC_SHA1 的使用引數指導:
NSMutableData * derivedKey = [NSMutableData dataWithLength:kAlgorithmKeySize]; int result = PKCS5_PBKDF2_HMAC_SHA1(password.UTF8String, (int)[password length], salt.bytes, (int)[salt length], 10000, (int)[derivedKey length], derivedKey.mutableBytes);
相關推薦
SHA256加密-各種語言版本的基於HMAC-SHA256的base64加密
語言包含: Javascript ,PHP,Java,Groovy,C#,Objective C,Go,Ruby,Python,Perl,Dart,Swift,Rust,Powershell。 Javascript HMAC SHA256 Run the cod
hiho第一週A+B各種語言版本(內容來自hiho)
using System; public class AplusB { private static void Main() { string line; while((line = Console.ReadLine()) != null)
Blowfish各種語言版本
objective-c的blowfish實現程式碼,沒有找到。於是使用c語言的程式碼來實現blowfish加密解密演算法。另外附上其他兩個版本的blowfish。 一:C版 1、blowfish.c#include <stdio.h> #include <
各種語言HMAC SHA256實現
語言包含: Javascript ,PHP,Java,Groovy,C#,Objective C,Go,Ruby,Python,Perl,Dart,Swift,Rust,Powershell。 1. Javascript HMAC SHA256 R
各種語言HMAC SHA256實現以及Base64編碼注意事項
語言包含: Javascript ,PHP,Java,Groovy,C#,Objective C,Go,Ruby,Python,Perl,Dart,Swift,Rust,Powershell。Javascript HMAC SHA256 Run the code onl
python接口自動化23-簽名(signature)鑒權(authentication)之加密(HEX、MD5、HMAC-SHA256)
-s .com 常用 lower byte 時間戳 python接口 信息 block 前言 開放的接口為了避免被別人亂調用,浪費服務器資源,這就涉及到簽名(Signature)加密了API 使用簽名方法(Signature)對接口進行鑒權(Authentication
【加密】各種加密(打亂)易語言程式碼的sdk程式碼
[部分內容來自網際網路] VMP保護------------------------------------------------------------------------------- 置入程式碼 ({ 235, 16, 86, 77, 80, 114, 111,
HMAC-SHA1各語言版本實現
在各大開放平臺大行其道的網際網路開發潮流中,呼叫各平臺的API介面過程中,無一例外都會用到計算簽名值(sig值)。而在各種計算簽名的方法中,經常被採用的就是HMAC-SHA1,現對HMAC-SHA1做一個簡單的介紹: HMAC,雜湊訊息鑑別碼
URL引數對稱加密---PHP語言版本
一. 基礎方法 為了簡單易行,設計上,我將所有引數以json物件封裝起來,然後再進行加密: 1. json封裝物件 $data = json_encode($data); 2.異或對稱加密(兩種方法,自行選擇) /** * 方法1
用樹莓派實現RGB LED的顏色控制——C語言版本號
個數 hang clu 代碼 stdio.h 標準 tro color sage 用樹莓派實現RGB LED的顏色控制 RGB色彩模式是工業界的一種顏色標準。是通過對紅(R)、綠(G)、藍(B)三個顏色通道的變化
php實現在不同國家顯示網站的不同語言版本
env com tip 字符 判斷 當前 location cli iss 首先,你的網站本身要擁有多個語言版本。不然的話你就只能用JS去轉化了。 1.通過ip去定位,這個要引用到第三方的接口進行數據的完整返回,但是不知道是我的網速太慢還是什麽原因,個人覺得這個方法會卡頓:
基於私鑰加密公鑰解密的RSA算法C#實現方法
第一個 inter tro 十進制 函數 軟件 產生 ++ 原創 本文實例講述了基於私鑰加密公鑰解密的RSA算法C#實現方法,是一種應用十分廣泛的算法。分享給大家供大家參考之用。具體方法如下: 一、概述 RSA算法是第一個能同時用於加密和數字簽名的算法,也易於理解和操
一個好用的字符過濾,差異匹配補丁的擴展庫,各語言版本
system cleanup http ups linked 默認 javascrip lai python diff-match-patchgithub地址 支持c,java,javascript,lua,object-c,python https://github.
WinForm多語言版本實戰項目演練
WinForm C# .NET 多語言版本 本地化 一、課程介紹關於如何實現“WinForm多語言版本”網上有很多實現技術方案,可以說是“琳瑯滿目”,"包羅萬象"。俗話說的好:一千個讀者就有一千個哈姆雷特!如果您工作中恰好也遇到這種開發需求,但是為了一個自上手簡單、維護
IDEA裏如何實現自動導入包和導入包優化的設置?(適合各種語言)(圖文詳解)
pic add 分享 str sca 詳解 個人博客 optimize html 不多說,直接上幹貨! 前言 為什麽需要自動導入包?為什麽需要導入包優化呢? 答: IDEA裏如何實現自動導
IDEA學習系列之剖析IDEA裏的Code Style(適合各種語言)(不斷更新)(圖文詳解)
ESS javascrip 挖掘 python pre scrip 學習 裏的 yaml 不多說,直接上幹貨! File -> Settings -> Editor -> Code Style
[日常] Go語言聖經-基於select的多路復用習題
string con print text 習題 true ont IT 語句 練習 8.8: 使用select來改造8.3節中的echo服務器,為其增加超時,這樣服務器可以在客戶端10秒中沒有任何喊話時自動斷開連接。 reverb3.go package main i
【Postgresql】postgresql9.3.9版本基於流復制方式雙機熱備方案
postgresql 雙機熱備 流復制 9.3.9 系統環境:centos6.5數據庫版本: postgres9.3.9虛擬機2臺:Master:10.0.2.160Slave:10.0.2.69數據存儲位置:/usr/local/pgsql/data/ 安裝pgsql數據庫 安裝過程可參
qsort歸納學習(c語言版本)
serve www. 返回 char s regexp ever char* str ret 參考:https://www.cnblogs.com/ForeverJoker/archive/2013/05/25/qsort-sort.html 包含在<stdlib.h
1003 Emergency(25 分)C語言版本(提問求解答)
paths sub amount ble max lis sam ams marked 1003 Emergency(25 分) As an emergency rescue team leader of a city, you are given a special ma