任何人都知道如何计算3DES密钥的校验值(KCV)吗?
示例键DBFE96D0A5F09D24
的检查值为5B4C8BED
我看到了C#的示例,但没有看到Java。
答案 0 :(得分:0)
尝试以下很大程度上基于“ Calculating the Key Check Value of a key”文章中提供的代码的代码:
package javaapplication28;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.GeneralSecurityException;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.util.encoders.Hex;
public class JavaApplication28 {
public static void main(String[] args) throws GeneralSecurityException {
String key = "DBFE96D0A5F09D24";
byte[] bytes = key.getBytes();
String kcv = JavaApplication28.getKcv(bytes);
System.out.println("key=" + key + ", kcv=" + kcv);
}
// Heavily based on code provided in the article "Calculating the Key Check Value of a key".
// https://hk.saowen.com/a/55c92a558ccb3e062970bab22eaa83c5c4d121878925c05f7949b988f61963e3
private static String getKcv(byte[] key) throws GeneralSecurityException {
// Add Bouncy Castle Security Provider
Security.addProvider(new BouncyCastleProvider());
// Construct a Secret Key from the given key
SecretKey skey = new SecretKeySpec(key, "DESede");
// Instantiate a DESede Cipher
Cipher encrypter = Cipher.getInstance("DESede/ECB/NoPadding", "BC");
// Initialize the cipher with the key in Encrypt mode
encrypter.init(Cipher.ENCRYPT_MODE, skey);
// Encrypt an 8-byte null array with the cipher and return the first 6 Hex digits of the result
return Hex.toHexString(encrypter.doFinal(new byte[8])).substring(0, 6).toUpperCase();
}
}
这是使用键值运行时的输出:
run:
key=DBFE96D0A5F09D24, kcv=F153C7
BUILD SUCCESSFUL (total time: 0 seconds)
注意:
它不会不返回您指定的KCV。但是,它确实与使用在线验证器http://tripledes.online-domain-tools.com/时返回的值匹配,如下面的屏幕截图所示。