Difference between SHA256withRSA and SHA256 then RSA

后端 未结 2 1667
小鲜肉
小鲜肉 2020-12-07 17:38

What is the difference between compute a signature with the following two methods?

  1. Compute a signature with Signature.getInstance(\"SHA256withRSA\")
2条回答
  •  感情败类
    2020-12-07 18:20

    ******Without BouncyCastle I adjusted your solution folowing the mkl's answer steps******

    import java.security.MessageDigest;
    import java.security.PrivateKey;
    import java.security.Signature;
    import java.security.interfaces.RSAPrivateCrtKey;
    
    import sun.security.rsa.RSACore;
    import sun.security.rsa.RSAPadding;
    import sun.security.util.DerOutputStream;
    import sun.security.util.DerValue;
    import sun.security.x509.AlgIdDSA;
    import sun.security.x509.AlgorithmId;
    
    public class MySHA256 {
    
        public static void main(String[] args) throws Exception {
    
            String s = "1234";
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(s.getBytes());
            byte[] outputDigest = messageDigest.digest(); 
            //compute SHA256 first
            DerOutputStream out = new DerOutputStream();
            new AlgorithmId(AlgIdDSA.SHA256_oid).encode(out);
            out.putOctetString(outputDigest);
            DerValue result = new DerValue(DerValue.tag_Sequence, out.toByteArray());
            byte[] encoded = result.toByteArray();      
            //sign SHA256 with RSA
            PrivateKey privateKey = Share.loadPk8("D:/key.pk8");
            RSAPrivateCrtKey pkRSA = (RSAPrivateCrtKey)privateKey;
            int keySize = RSACore.getByteLength(pkRSA);
            RSAPadding padding = RSAPadding.getInstance(RSAPadding.PAD_BLOCKTYPE_1, keySize, null);
            byte[] padded = padding.pad(encoded);
            byte[] signed = RSACore.rsa(padded, pkRSA, true);
            System.out.println(bytesToHex(signed));
    
    
            //compute SHA256withRSA as a single step
            Signature rsaSha256Signature = Signature.getInstance("SHA256withRSA");
            rsaSha256Signature.initSign(privateKey);
            rsaSha256Signature.update(s.getBytes());
            byte[] signed2 = rsaSha256Signature.sign();
            System.out.println(bytesToHex(signed2));
        }
    
        public static String bytesToHex(byte[] bytes) {
            final char[] hexArray = "0123456789ABCDEF".toCharArray();
            char[] hexChars = new char[bytes.length * 2];
            for ( int j = 0; j < bytes.length; j++ ) {
                int v = bytes[j] & 0xFF;
                hexChars[j * 2] = hexArray[v >>> 4];
                hexChars[j * 2 + 1] = hexArray[v & 0x0F];
            }
            return new String(hexChars);
        }
    
    
    
    }
    

提交回复
热议问题