Java 大整数->;字节[]->;大整数。看起来相等,但如果语句失败

Java 大整数->;字节[]->;大整数。看起来相等,但如果语句失败,java,eclipse,encryption,byte,biginteger,Java,Eclipse,Encryption,Byte,Biginteger,我正在玩弄一个为自己存储公钥的想法。为此,我需要在某种变量中转换BigInteger,然后从该值重新创建BigInteger 我已经通过Stackoverflow进行了搜索,以找到实现这一点的最佳方法是使用字节[] 这是我在Eclipse中的代码: import java.math.BigInteger; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.interf

我正在玩弄一个为自己存储公钥的想法。为此,我需要在某种变量中转换BigInteger,然后从该值重新创建BigInteger

我已经通过Stackoverflow进行了搜索,以找到实现这一点的最佳方法是使用字节[]

这是我在Eclipse中的代码:

import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPublicKey;

public class Vaja2 {
    public static void main(String[] args){
        try {

            // Create RSA Keypair (to obtain a BigInteger)
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(1024);
            KeyPair keypair = kpg.generateKeyPair();

            // Extract the public key
            RSAPublicKey publicKey = (RSAPublicKey) keypair.getPublic();

            // Get the public Exponent from the public key, I have BigInteger now.
            BigInteger pkPublicExBI = publicKey.getPublicExponent();

            //Try this:   BigInteger -> byte-> BigInteger
            byte[] pkModByte = pkPublicExBI.toByteArray();
            BigInteger pkPublicExBIrecreated = new BigInteger(pkModByte);


            // Show Results
            System.out.println("Original BigInteger:    " + pkPublicExBI);
            System.out.println("Recreated BigInteger:   " + pkPublicExBIrecreated);

            if (pkPublicExBI == pkPublicExBIrecreated) {
                System.out.println("\nThey are equal");
            }
            else {
                System.out.println("\nThey are NOT equal");
            }


        } catch (Exception e) {
            // Nothing happens
        }

    }
}
这是Eclipse控制台中显示的结果

原始大整数:65537
重新创建的BigInteger:65537
他们不平等
if语句告诉我,两个大整数不相等。但在控制台中,我认为它们都等于65537

我的问题是:

  • 为什么“if”语句失败

  • 你会建议我如何使代码与众不同。假设程序要求将公钥存储在notepad.exe或类似的文本编码程序(将使用ASCII)中

  • 比较对象时使用
    .equals()
    而不是
    =
    =
    将比较对象的引用,而
    .equals()
    将检查它们是否具有相同的值。因为两个对象很少有相同的引用,所以除了比较基本类型(int、char,但String不是基本类型!)之外,您不应该使用
    =
    ,因为这无关紧要

    所以你想要:

    if (pkPublicExBI.equals(pkPublicExBIrecreated)) {
    
    而不是

    if (pkPublicExBI == pkPublicExBIrecreated) {
    

    请改用这个
    pkPublicExBI.equals(pkPublicExBIrecreated)

    它们是对象比较参考文献。要检查值是否相等,请改用.equals()。了解equals()和==之间的区别。很好的回答谢谢你的正确回答,并花时间向我解释为什么我的答案是正确的。(我正在从C走向Java编程和面向类编程)你的推理是正确的,但解释是错误的。==运算符比较对象标识。“内存中的地址”的概念比使用Java可以访问的级别低得多。无论在理论上还是在实践中,JVM都会在堆中移动对象,因此同一对象很可能出现在不同的地址上。
    pkPublicExBI == pkPublicExBIrecreated