-3

Anyone know how to calculate check value (KCV) for a 3DES key?

Example the Check Value for key DBFE96D0A5F09D24 is 5B4C8BED

I saw sample for C# but not Java.

Alvin
  • 8,219
  • 25
  • 96
  • 177
  • Why is your KCV 8 digits long? Shouldn't it be 6 hex digits? See http://www.emvlab.org/keyshares/ : "The KCV is the "Key Check Value" for the key, calculated by assuming the key/components are 3DES keys, and encrypting a string of binary zeroes. **The KCV is the first six hex digits of the resulting ciphertext**." – skomisa Nov 09 '18 at 07:27

1 Answers1

2

Try this code which is heavily based on that provided in the article "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();
    }
}

This is the output when run using your key value:

run:
key=DBFE96D0A5F09D24, kcv=F153C7
BUILD SUCCESSFUL (total time: 0 seconds)

Notes:

  1. The code requires the Bouncy Castle jar file bcprov-ext-jdk15on-160.jar which you can download from here: https://www.bouncycastle.org/example.html
  2. It does NOT return the KCV that you specified. However, it does match the value returned when using the online validator http://tripledes.online-domain-tools.com/ as shown in the screen shot below.

    online3Des

skomisa
  • 16,436
  • 7
  • 61
  • 102