【问题标题】:Encrypt a password with Salesforce Apex using SHA1使用 SHA1 使用 Salesforce Apex 加密密码
【发布时间】:2022-01-06 17:27:06
【问题描述】:

我需要编写加密密码的 Salesforce Apex 代码。这用于轮询其凭据必须遵循此加密模型的外部 API。

API 密码加密需要 3 个参数:用户密码、随机 16 字符字符串和格式为 2022-01-06T17:01:22Z 的时间戳。

公式为:outputKey = Base64(SHA1($randomString + $timestamp+ SHA1($userPassword)))

干净的加密会产生以下结果 输入:
密码:花生酱 randomString:uniqueCode123456 时间戳:2022-01-06T17:01:22Z

预期输出:FApp+ayrBcB5XUhygr9lFJLK1p0=

我的代码当前运行如下,但没有提供预期的输出。 (注意:为简单起见,这里对变量 uniqueCode 和 timestamp 进行了硬编码,但它们是在每次 API 调用时生成的。

String uniqueCode = 'uniqueCode123456';
String timestamp = '2015-09-30T14:12:15Z'; 
Blob password = Blob.valueOf(‘peanutButter’);
Blob hashPassword = Crypto.generateDigest('SHA1', password); 
String combinedPassword = uniqueCode + timeStamp + EncodingUtil.convertToHex(hashPassword);

Blob blobCombinedPassword = Blob.valueOf(combinedPassword);
Blob hashedFull = Crypto.generateDigest('SHA1', blobCombinedPassword);
String outputKey = EncodingUtil.base64encode (hashedFull);

我需要什么不同的运行方式来生成正确的输出?

谢谢

【问题讨论】:

  • 首先 - SHA 是哈希 fn,而不是加密。非常不一样。第二 - convertToHex 你确定你需要连接 psswd 哈希的十六进制字符串吗?它也可以是字节数组连接,或其他编码。

标签: encryption salesforce apex sha1


【解决方案1】:

这会为您的输入数据产生相同的结果:

Blob pwd = Crypto.generateDigest('SHA1', Blob.valueOf('peanutButter'));
Blob full = Blob.valueOf('uniqueCode1234562022-01-06T17:01:22Z');
String combo = EncodingUtil.convertToHex(full) + EncodingUtil.convertToHex(pwd);
Blob comboBlob = EncodingUtil.convertFromHex(combo);
Blob finalBlob = Crypto.generateDigest('SHA1', comboBlob);
String finalStr = EncodingUtil.base64Encode(finalBlob);
System.debug(finalStr); // Prints FApp+ayrBcB5XUhygr9lFJLK1p0=

因此,您的错误是将 combinedPassword 解释为文本,而第二次转换为 Blob 时却不是。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 2014-12-03
    • 1970-01-01
    • 2012-06-26
    相关资源
    最近更新 更多