代码之家  ›  专栏  ›  技术社区  ›  Alvin

从3des键计算kcv

  •  -3
  • Alvin  · 技术社区  · 6 年前

    有人知道如何计算3des键的检查值(kcv)吗?

    键的检查值示例 DBFE96D0A5F09D24 5B4C8BED

    我看到了C的样本,但没有Java。

    1 回复  |  直到 6 年前
        1
  •  0
  •   skomisa    6 年前

    请尝试此代码,它主要基于文章中提供的代码。” 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)
    

    笔记:

    1. 代码需要bouncy castle jar文件 bcprov-ext-jdk15on-160.jar文件 你可以从这里下载: https://www.bouncycastle.org/example.html
    2. 它确实 不是 返回指定的KCV。但是,它与使用联机验证器时返回的值匹配 http://tripledes.online-domain-tools.com/ 如下图所示。

      online3Des