0

暗号アルゴリズムとして RSA を使用し、ハッシュ関数として SHA-1 を使用して独自の署名関数を実装したいので、これら 2 つの関数を実装しました。

public byte[] mySign(byte[] aMessage){
    try{
        // get an instance of a cipher with RSA with ENCRYPT_MODE
        // Init the signature with the private key
          Cipher cipher = Cipher.getInstance("RSA");
          cipher.init(Cipher.ENCRYPT_MODE, this.thePrivateKey);

        // get an instance of the java.security.MessageDigest with sha1
             MessageDigest meassDs = MessageDigest.getInstance("SHA-1");

        // process the digest
             meassDs.update(aMessage);
             byte[] digest = meassDs.digest();

            byte [] signature = cipher.doFinal(digest);

        // return the encrypted digest
        return signature;

    }catch(Exception e){
        System.out.println(e.getMessage()+"Signature error");
        e.printStackTrace();
        return null;
    }

}



public boolean myCheckSignature(byte[] aMessage, byte[] aSignature, PublicKey aPK){
    try{
        // get an instance of a cipher with RSA with DECRYPT_MODE
        // Init the signature with the public key
          Cipher cipher = Cipher.getInstance("RSA");
          cipher.init(Cipher.DECRYPT_MODE, aPK);

        // decrypt the signature
             byte [] digest1 = cipher.doFinal(aSignature);

        // get an instance of the java.security.MessageDigest with sha1
             MessageDigest meassDs = MessageDigest.getInstance("SHA-1");

        // process the digest
             meassDs.update(aMessage);
             byte[] digest2 = meassDs.digest();

        // check if digest1 == digest2
        if (digest1 == digest2)
        return true;
        else
            return false;

    }catch(Exception e){
        System.out.println("Verify signature error");
        e.printStackTrace();
        return false;
    }
}   

次に、これらの関数を使用すると、結果として常に false が得られます。これは、関数が正しく機能していないことを意味します。

byte[] message = "hello world".getBytes();
byte[] signature;

signature = mySign(message );
boolean bool = myCheckSignature(message , signature, thePublicKey);
System.out.println(bool);
4

1 に答える 1

1

あなたの要件が

java.security.Signature の代替を使用して署名を作成するメソッドを実装する

全体として疑問があります(質問へのコメントに記載されているように)、ソリューションを改善できます。

特に、myCheckSignatureコードにエラーがあります:

// check if digest1 == digest2
if (digest1 == digest2)
    return true;
else
    return false;

(digest1 == digest2)内容が等しい 2 つの配列があるかどうかではなく、同一の配列オブジェクトがあるかどうかをチェックします。

あなたが本当にやりたいことは、

if (Arrays.equals(digest1, digest2))
    return true;
else
    return false;

またはよりコンパクトに

return Arrays.equals(digest1, digest2);

Arraysパッケージ内のユーティリティ クラスjava.utilです。


ところで、あなたはそうします

byte[] message = "hello world".getBytes();

getBytes文字エンコーディングを明示的に選択しないと、異なるプラットフォームまたは異なる Java バージョンで異なる結果になる可能性があります。この文脈で起こってはいけないこと!

于 2016-01-12T17:38:27.550 に答える