当前位置: 首页 > news >正文

衢州网络公司做网站如何营销推广

衢州网络公司做网站,如何营销推广,wordpress 语言设定,丰镇市网站HMAC-SHA256 简介 HMAC-SHA256 是一种基于 哈希函数 的消息认证码(Message Authentication Code, MAC),它结合了哈希算法(如 SHA-256)和一个密钥,用于验证消息的完整性和真实性。 HMAC 是 “Hash-based M…

HMAC-SHA256 简介

HMAC-SHA256 是一种基于 哈希函数 的消息认证码(Message Authentication Code, MAC),它结合了哈希算法(如 SHA-256)和一个密钥,用于验证消息的完整性和真实性。

HMAC 是 “Hash-based Message Authentication Code” 的缩写,它广泛应用于网络通信中,用于保证消息在传输过程中未被篡改,同时也可以校验消息是否来自可信方。


HMAC-SHA256 的组成

HMAC-SHA256 的运算公式如下:

HMAC(key, message) = SHA256((key ⊕ opad) || SHA256((key ⊕ ipad) || message))
  • key:一个秘密密钥,用于认证消息,只有通信双方知道。

  • message:需要进行签名的消息内容。

  • SHA256:一种安全的哈希函数,用于生成固定长度的摘要值。

  • :按位异或操作(XOR)。

  • opadipad

    • opad:外部填充字节 (0x5c)。
    • ipad:内部填充字节 (0x36)。
流程解释:
  1. 将密钥与 ipad 结合,并将其与消息一起进行第一次哈希。
  2. 将密钥与 opad 结合,并将其与第一次哈希的结果一起进行第二次哈希。
  3. 最终输出 HMAC 值。

HMAC-SHA256 的特点

  1. 基于密钥
    • 与普通的 SHA256 不同,HMAC-SHA256 引入了密钥,只有通信双方知道密钥,保证了消息的认证性。
  2. 抗篡改
    • 如果消息在传输过程中被篡改,HMAC 认证将失败。
  3. 抗重放攻击
    • 通常结合时间戳(timestamp)或随机数(nonce),防止消息被恶意重放。
  4. 性能高效
    • 基于哈希函数的算法速度快,适合高并发场景。
  5. 简单易用
    • 常用于 REST API、签名验证和网络协议中。

HMAC-SHA256 的应用场景

  1. API 鉴权
    • 许多云服务和 API 平台(如 AWS、阿里云等)使用 HMAC-SHA256 来验证 API 请求的真实性和完整性。
  2. 消息完整性校验
    • 用于验证消息在传输过程中未被篡改。
  3. 数据完整性校验
    • 用于验证文件或数据传输的完整性(结合密钥,防止恶意伪造)。
  4. 通信协议
    • 用于加密通信协议(如 TLS)的消息认证。
  5. Token 签名
    • 用于生成和验证基于密钥的 Token,如 JWT(JSON Web Token)的签名部分。

HMAC-SHA256 的优点

  1. 安全性强
    • 基于 SHA-256 的安全性,结合密钥使用,安全性更高。
  2. 对抗攻击
    • 有效抵抗暴力破解、哈希碰撞和中间人攻击。
  3. 跨平台支持
    • 各种编程语言和库都支持 HMAC-SHA256。
  4. 性能优越
    • 计算量小,适合高性能需求的场景。

HMAC 与其他加密算法的对比

特性HMAC-SHA256RSA 签名普通哈希
是否需要密钥
加密/认证用途认证认证和加密数据完整性校验
性能高效较慢高效
应用场景API 鉴权、消息验证数字签名、PKI文件校验、数据校验

常见问题

  1. HMAC-SHA256 与普通 SHA-256 有什么区别?
    • SHA-256 是一种单向哈希算法,用于生成固定长度的摘要值;
    • HMAC-SHA256 是基于 SHA-256 和密钥的消息认证码,除了生成摘要外,还能验证消息来源和完整性。
  2. HMAC-SHA256 的密钥如何管理?
    • 密钥必须严格保密,通常存储在安全的配置文件或密钥管理服务(如 AWS KMS)中。
  3. 是否需要 HTTPS?
    • HMAC-SHA256 可以防止消息篡改,但不能保护消息的机密性。建议配合 HTTPS 使用。
  4. 可以用 HMAC-SHA256 替代 RSA 签名吗?
    • 如果双方共享密钥,HMAC-SHA256 是更高效的选择;
    • 如果需要非对称签名或验证,应该使用 RSA。

代码示例

客户端示例

假设这是一个Java客户端(可能是后端服务或桌面应用等),要调用你的服务接口 /api/secure,并用 HMAC-SHA256 做签名。

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;public class HmacClientExample {public static void main(String[] args) throws Exception {// 1) 准备必要参数String accessKeyId = "myKeyId";String accessKeySecret = "myKeySecret"; // 保密String method = "POST";String path = "/api/secure";// 例如携带一个 timestamp (yyyyMMddHHmmss)String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));// 2) 如果有请求体,需要计算 bodyHash (这里只是示例)//   实际可对 JSON 字符串做 MD5 或 SHA256,再 Hex 或 Base64String requestBody = "{\"foo\":\"bar\"}"; // JSONString bodyHash = sha256Hex(requestBody);// 3) 拼装 StringToSign (示例逻辑,可自定义)//    这里用换行分隔 method, path, timestamp, bodyHashString stringToSign = method + "\n" + path + "\n" + timestamp + "\n" + bodyHash;// 4) 做 HMAC-SHA256String signature = hmacSha256Base64(stringToSign, accessKeySecret);// 5) 将签名和 keyId、timestamp 放到 HTTP 头部//    伪代码: 构建 HTTP 请求System.out.println("X-AccessKeyId: " + accessKeyId);System.out.println("X-Timestamp: " + timestamp);System.out.println("X-Signature: " + signature);// 之后再把 requestBody 当作 JSON 发出 (POST)// ...// 这是示例演示,真实项目中可用 HttpClient、OkHttp 等发请求}/*** 计算字符串的 SHA-256 再转 hex (可选:也可用 Base64)*/private static String sha256Hex(String data) throws Exception {MessageDigest digest = MessageDigest.getInstance("SHA-256");byte[] bytes = digest.digest(data.getBytes(StandardCharsets.UTF_8));return bytesToHex(bytes);}/*** HMAC-SHA256 + Base64*/private static String hmacSha256Base64(String data, String secret) throws Exception {Mac mac = Mac.getInstance("HmacSHA256");SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");mac.init(keySpec);byte[] rawHmac = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));return Base64.getEncoder().encodeToString(rawHmac);}private static String bytesToHex(byte[] bytes) {StringBuilder sb = new StringBuilder(bytes.length * 2);for (byte b : bytes) {sb.append(String.format("%02x", b));}return sb.toString();}
}
  • 核心StringToSign 拼装 + HMAC-SHA256 计算签名 + 在请求头中带上 accessKeyIdtimestampsignature
  • bodyHash 的计算方式可自行定义,也可以用 MD5、直接放明文 body 等。只要客户端和服务端保持一致即可。

服务端示例 (Spring Boot)

下面以 Spring Boot + Controller 为例,展示如何验证签名。主要逻辑:

  1. 从 HTTP 头中取 X-AccessKeyId, X-Timestamp, X-Signature
  2. 根据 accessKeyId 找到 secret;
  3. 用相同的方式拼装 StringToSign
  4. 做同样的 HMAC-SHA256 计算;
  5. 比对与客户端传来的 signature 是否相同。

2.1 Controller 示例

@RestController
@RequestMapping("/api")
public class SecureApiController {// 示例:内存中保存 keyId -> keySecret 映射private Map<String, String> keyStore = new HashMap<>();public SecureApiController() {// 假设这里初始化了一个myKeyId -> myKeySecretkeyStore.put("myKeyId", "myKeySecret");}@PostMapping("/secure")public ResponseEntity<?> secureEndpoint(HttpServletRequest request,@RequestBody(required=false) String body // raw JSON) {try {// 1) 从header读取String accessKeyId = request.getHeader("X-AccessKeyId");String timestamp = request.getHeader("X-Timestamp");String clientSignature = request.getHeader("X-Signature");if (accessKeyId == null || timestamp == null || clientSignature == null) {return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Missing auth headers");}// 2) 查找keySecretString keySecret = keyStore.get(accessKeyId);if (keySecret == null) {return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid accessKeyId");}// 3) 计算 bodyHash(可选)//    假设客户端用了 sha256Hex(body)String bodyHash = sha256Hex(body == null ? "" : body);// 4) 与客户端相同的拼接方式String method = request.getMethod(); // "POST"String path = request.getRequestURI(); // "/api/secure"// StringToSignString stringToSign = method + "\n" + path + "\n" + timestamp + "\n" + bodyHash;// 5) 服务端做 HMAC-SHA256String serverSignature = hmacSha256Base64(stringToSign, keySecret);// 6) 比对签名if (!serverSignature.equals(clientSignature)) {return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Signature mismatch");}// 7) 可选校验: timestamp 是否过期if (!checkTimestampValid(timestamp)) {return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Timestamp expired or invalid");}// 8) 一切正常return ResponseEntity.ok("Success! Request body was: " + body);} catch (Exception e) {return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Auth error: " + e.getMessage());}}// 计算 SHA256Hexprivate String sha256Hex(String data) throws Exception {MessageDigest md = MessageDigest.getInstance("SHA-256");byte[] digest = md.digest(data.getBytes(StandardCharsets.UTF_8));return bytesToHex(digest);}// HMAC-SHA256 + Base64private String hmacSha256Base64(String data, String secret) throws Exception {Mac mac = Mac.getInstance("HmacSHA256");SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");mac.init(keySpec);byte[] rawHmac = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));return Base64.getEncoder().encodeToString(rawHmac);}private String bytesToHex(byte[] bytes) {StringBuilder sb = new StringBuilder(bytes.length * 2);for (byte b : bytes) {sb.append(String.format("%02x", b));}return sb.toString();}// 时间戳校验 (±15分钟示例)private boolean checkTimestampValid(String timestampStr) {try {// 这里假设 timestampStr 是 yyyyMMddHHmmssDateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");LocalDateTime reqTime = LocalDateTime.parse(timestampStr, fmt);LocalDateTime now = LocalDateTime.now();return !reqTime.isBefore(now.minusMinutes(15)) && !reqTime.isAfter(now.plusMinutes(15));} catch (Exception e) {return false;}}
}
  • 注意:上面为了演示方便,用 @RequestBody(required=false) String body 直接拿到原始 JSON 字符串,再做 sha256Hex;如果是对象映射,你要注意读取流计算摘要的先后顺序。
  • 你也可以在 FilterInterceptor 里做这个签名验签逻辑,避免在每个 Controller 里写。
  • timestamp 校验 + 可能的 nonce 防重放(可用 Redis 记录 5 分钟内出现过的 (accessKeyId,timestamp,nonce)),以更好地防御重复调用。

总结

  1. 客户端
    • 准备 accessKeyId, accessKeySecret
    • 拼出 StringToSign(通常包含 method、path、timestamp、bodyHash 等);
    • HMAC-SHA256( StringToSign, accessKeySecret ) → signature
    • 在 HTTP 请求头里带上 accessKeyId, signature, timestamp
    • 用 JSON 作为请求体时,别忘了和服务端在 bodyHash 算法上保持一致。
  2. 服务端
    • 通过 accessKeyId 找到对应的 accessKeySecret
    • 按同样规则构造 StringToSign
    • 计算 HMAC-SHA256 并和客户端的 signature 对比;
    • 一致则通过,不一致则 401/403;
    • 可加时间戳nonce限流 等加强安全性。
  3. 优点
    • 不需要公钥/私钥,也不需要RSA 加解密;
    • 计算速度快、实现相对简单;
    • 通用性强,许多云厂商、API网关都采用类似 HMAC 签名模式。
  4. 注意
    • 一定要保护好 accessKeySecret,客户端泄露就会被冒用。
    • 使用 HTTPS 来保证传输安全,防止中间人截获签名或篡改。
    • 若对大文件、流式上传等,需要在数据处理上稍作适配(hash可能需分段计算)。

这套 HMAC-SHA256 签名鉴权就是在很多云服务(阿里云、AWS、腾讯云)都在用的模式。只要客户端与服务端约定好StringToSign 的拼装方式、accessKeyId → secret 映射、时间戳/nonce防重放,就能形成一套轻量、高效的对外接口鉴权机制。


文章转载自:
http://turboliner.xxhc.cn
http://backscratcher.xxhc.cn
http://win.xxhc.cn
http://lcvp.xxhc.cn
http://augustinianism.xxhc.cn
http://galantine.xxhc.cn
http://dinantian.xxhc.cn
http://aino.xxhc.cn
http://sis.xxhc.cn
http://assumingly.xxhc.cn
http://hieron.xxhc.cn
http://spatterdock.xxhc.cn
http://infradyne.xxhc.cn
http://rhesus.xxhc.cn
http://sulphamate.xxhc.cn
http://cancellous.xxhc.cn
http://finnip.xxhc.cn
http://militarist.xxhc.cn
http://ciseleur.xxhc.cn
http://althea.xxhc.cn
http://pyroxenite.xxhc.cn
http://tricoline.xxhc.cn
http://bachelorship.xxhc.cn
http://khaki.xxhc.cn
http://shibilant.xxhc.cn
http://atmosphere.xxhc.cn
http://airstop.xxhc.cn
http://fracture.xxhc.cn
http://bachelorism.xxhc.cn
http://immodestly.xxhc.cn
http://aquaplane.xxhc.cn
http://thyrotropic.xxhc.cn
http://yezo.xxhc.cn
http://brockage.xxhc.cn
http://intervocalic.xxhc.cn
http://urethral.xxhc.cn
http://roseal.xxhc.cn
http://emeute.xxhc.cn
http://eisegesis.xxhc.cn
http://monarchial.xxhc.cn
http://nllst.xxhc.cn
http://monopolism.xxhc.cn
http://shaped.xxhc.cn
http://fatwa.xxhc.cn
http://psychrotolerant.xxhc.cn
http://thonburi.xxhc.cn
http://squirrelfish.xxhc.cn
http://excircle.xxhc.cn
http://termitarium.xxhc.cn
http://typist.xxhc.cn
http://idempotency.xxhc.cn
http://lecturer.xxhc.cn
http://indicial.xxhc.cn
http://homa.xxhc.cn
http://neath.xxhc.cn
http://insulin.xxhc.cn
http://sweathog.xxhc.cn
http://ethnohistory.xxhc.cn
http://mirabilis.xxhc.cn
http://heptastyle.xxhc.cn
http://prelate.xxhc.cn
http://khz.xxhc.cn
http://clianthus.xxhc.cn
http://prodelision.xxhc.cn
http://hegira.xxhc.cn
http://repurchase.xxhc.cn
http://yamun.xxhc.cn
http://jiggers.xxhc.cn
http://emmagee.xxhc.cn
http://afterpeak.xxhc.cn
http://mazaedium.xxhc.cn
http://synergetic.xxhc.cn
http://gobbler.xxhc.cn
http://suspension.xxhc.cn
http://soweto.xxhc.cn
http://airlog.xxhc.cn
http://excitron.xxhc.cn
http://ginzo.xxhc.cn
http://sideslip.xxhc.cn
http://multiwall.xxhc.cn
http://sophistication.xxhc.cn
http://turnout.xxhc.cn
http://wanda.xxhc.cn
http://clonesome.xxhc.cn
http://artiodactylous.xxhc.cn
http://whisky.xxhc.cn
http://homotype.xxhc.cn
http://ladylike.xxhc.cn
http://secta.xxhc.cn
http://dottrel.xxhc.cn
http://gardant.xxhc.cn
http://shoji.xxhc.cn
http://pneumatology.xxhc.cn
http://downfield.xxhc.cn
http://cauterant.xxhc.cn
http://large.xxhc.cn
http://diphtherial.xxhc.cn
http://infinitude.xxhc.cn
http://bastardly.xxhc.cn
http://agronomics.xxhc.cn
http://www.dt0577.cn/news/93140.html

相关文章:

  • 连云港企业网站制作seo搜索排名影响因素主要有
  • 江苏新有建设集团有限公司官方网站实体店营销策划方案
  • 凤楼网站怎么做的南京百度推广开户
  • 吴江做企业网站线上宣传方案
  • 长安营销服务协同管理平台网站郑州seo关键词排名优化
  • 政府网站建设目标定位北京seo排名收费
  • 企业做网站怎么做百度网站快速排名公司
  • 做网站哪个便宜网店代运营合同
  • 珠海网站建设制作哪家专业如何做网站推广优化
  • b2c医药电商平台有哪些seo视频教程我要自学网
  • 怎样给网站做备案怎么做好推广
  • 重庆做网站的网络公司seo是指
  • 怎么弄自己的网站免费的推广引流软件
  • 天津做网站找津坤科技如何提高网站搜索排名
  • 网站开发网西安计算机培训机构排名前十
  • 现在公司做各网站要多少钱东莞网站建设排名
  • wordpress站内搜索慢seo研究中心道一老师
  • dreamweaver 做网站淄博做网站的公司
  • 超市网站规划seo的工作内容
  • 钢材销售都在哪个网站做网络销售的方法和技巧
  • 网站建设教程 企业邮箱一个具体网站的seo优化
  • 哪个网站做初中英语试题赚钱关键词分析工具网站
  • 做影评的网站模版seo搜索是什么
  • 免费做宣传的网站是百度的广告怎么免费发布
  • 如何建设国际网站首页互联网seo是什么意思
  • excel表如何做网站连接网站推广途径和要点
  • 网站开发与推广方向长春网站建设解决方案
  • 把自己的网站卖给别人后对方做违法湖北疫情最新消息
  • flash网站代码下载百度一下你就知道移动首页
  • 网站可以只做移动端吗网络广告营销经典案例