【问题标题】:Compare PublicKey object in java比较 java 中的 PublicKey 对象
【发布时间】:2014-01-20 10:10:09
【问题描述】:

我有两个 PublicKey 对象。我想比较两者是否相等或使用 java 安全 API 或充气城堡 API 检查哪个是最新对象。我怎样才能做到这一点?

【问题讨论】:

  • .equals() 没用? “哪个是最新的”是什么意思
  • 我想知道。我是否可以比较 PublicKey 并检查两个 PublicKey 对象之间哪个更新了
  • @Henry 我确实看到 JCE 中的RSAPublicKey 实现了.equals(),但我不确定PublicKey 实例必须 覆盖.equals()。它没有在 JavaDoc 中定义(它可以在有关如何实现 Cryptographic Provider 的文档中定义,但我不认为它是)

标签: java security bouncycastle spongycastle


【解决方案1】:

您可以使用equals

if (!key.equals(copyKey)){
    System.out.println("not equals!");
}

或检查键的哈希码

if (key.hashCode() != copyKey.hashCode())
{
    System.out.println("public key hashCode check failed");
}

或者比较两个公钥的十六进制字符串

String encodedKey1 = new String(Hex.encode(key1.getEncoded()));
String encodedKey2 = new String(Hex.encode(key2.getEncoded()));

if (!encodedKey1.equals(encodedKey2)){
    System.out.println("not equals!");
}

您在 Bouncy Castle 测试中有很多关键的比较和检查示例,请查看 org.bouncycastle.jce.provider.test 包以获取一些代码。 BC 不是绝对必要的,您可以与默认的 java 安全类进行比较。

【讨论】:

    【解决方案2】:

    通常使用某种 ID 比较公钥。这取决于如何计算密钥 ID 的协议。最好的方法可能是遵守 PKCS#11 规范,该规范定义了计算密钥 ID 的方法。

    创建日期不是密钥本身的组成部分。要么你必须在别处定义它,要么你应该使用一个公钥容器,比如 X509 证书。请注意,您可以使用(十六进制表示的)密钥 ID 在地图中查找创建日期。

    最好在模数上使用 SHA-1 哈希作为 ID。公钥和私钥的模数相同,每个密钥对的模数应该不同。以下代码计算 RSA 公钥的 ID。

    显然,您也可以随时直接比较两个键的模数。不过,密钥 ID 更容易存储。

    public class CreateRSAPublicKeyID {
    
        /**
         * Creates a key ID for a given key.
         * 
         * @param key the key
         * @return the key ID for the given key
         */
        public static byte[] createKeyID(Key key) {
    
            if (key instanceof RSAKey) {
                RSAKey rsaKey = (RSAKey) key;
                BigInteger modulus = rsaKey.getModulus();
                if (modulus.bitLength() % Byte.SIZE != 0) {
                    throw new IllegalArgumentException("This method currently only works with RSA key sizes that are a multiple of 8 in bits");
                }
                final byte[] modulusData = i2os(modulus, modulus.bitLength() / Byte.SIZE);
                MessageDigest sha1;
                try {
                    sha1 = MessageDigest.getInstance("SHA-1");
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("SHA-1 message digest should be available in any Java SE runtime", e);
                }
                return sha1.digest(modulusData);
            }
    
            throw new UnsupportedOperationException("Key type not supported");
        }
    
        /**
         * Integer to octet string (I2OS) creates a fixed size, left padded, big-endian octet string representation for
         * a given integer.
         * 
         * @param i the integer
         * @param octets the number of octets (bytes)
         * @return the octet string representation of i
         */
        public static byte[] i2os(BigInteger i, int octets) {
    
            if (i.bitLength() > octets * Byte.SIZE) {
                throw new IllegalArgumentException("i does not fit in " + octets + " octets");
            }
    
            final byte[] is = i.toByteArray();
            if (is.length == octets) {
                return is;
            }
    
            final byte[] ius = new byte[octets];
            if (is.length == octets + 1) {
                System.arraycopy(is, 1, ius, 0, octets);
            } else {
                System.arraycopy(is, 0, ius, octets - is.length, is.length);
            }
            return ius;
        }
    
        public static String toHex(byte[] data) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.length; i++) {
                sb.append(String.format("%02X", data[i]));
            }
            return sb.toString();
        }
    
        public static void main(String[] args) throws Exception {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(2048);
            KeyPair pair = kpg.generateKeyPair();
            byte[] keyID = createKeyID(pair.getPublic());
            System.out.println(toHex(keyID));
        }
    }
    

    请注意,getModulus() 命令可能与某些密钥库不兼容(例如那些代表 HSM 令牌或智能卡的密钥库)。

    【讨论】:

      【解决方案3】:

      看看Oracle's documentation,我想你可以用它的3个getter比较PublicKey:getAlgorithm,getEncoded,getFormat这样做:

      oldKey.getAlgorithm().equals(newKey.getAlgorithm()) 等等。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-09
        • 2016-09-12
        • 1970-01-01
        • 1970-01-01
        • 2012-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多