请尝试此代码,它主要基于文章中提供的代码。”
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)
笔记:
-
代码需要bouncy castle jar文件
bcprov-ext-jdk15on-160.jar文件
你可以从这里下载:
https://www.bouncycastle.org/example.html
-
它确实
不是
返回指定的KCV。但是,它与使用联机验证器时返回的值匹配
http://tripledes.online-domain-tools.com/
如下图所示。