· 7 years ago · Nov 09, 2018, 08:50 AM
1package javaapplication28;
2
3import org.bouncycastle.jce.provider.BouncyCastleProvider;
4import java.security.GeneralSecurityException;
5import java.security.Security;
6import javax.crypto.Cipher;
7import javax.crypto.SecretKey;
8import javax.crypto.spec.SecretKeySpec;
9import org.bouncycastle.util.encoders.Hex;
10
11public class JavaApplication28 {
12
13 public static void main(String[] args) throws GeneralSecurityException {
14
15 String key = "DBFE96D0A5F09D24";
16 byte[] bytes = key.getBytes();
17 String kcv = JavaApplication28.getKcv(bytes);
18 System.out.println("key=" + key + ", kcv=" + kcv);
19 }
20
21 // Heavily based on code provided in the article "Calculating the Key Check Value of a key".
22 // https://hk.saowen.com/a/55c92a558ccb3e062970bab22eaa83c5c4d121878925c05f7949b988f61963e3
23 private static String getKcv(byte[] key) throws GeneralSecurityException {
24 // Add Bouncy Castle Security Provider
25 Security.addProvider(new BouncyCastleProvider());
26 // Construct a Secret Key from the given key
27 SecretKey skey = new SecretKeySpec(key, "DESede");
28 // Instantiate a DESede Cipher
29 Cipher encrypter = Cipher.getInstance("DESede/ECB/NoPadding", "BC");
30 // Initialize the cipher with the key in Encrypt mode
31 encrypter.init(Cipher.ENCRYPT_MODE, skey);
32 // Encrypt an 8-byte null array with the cipher and return the first 6 Hex digits of the result
33 return Hex.toHexString(encrypter.doFinal(new byte[8])).substring(0, 6).toUpperCase();
34 }
35}
36
37run:
38key=DBFE96D0A5F09D24, kcv=F153C7
39BUILD SUCCESSFUL (total time: 0 seconds)