none
Generate signature using sha256 with rsa2048 (PKCS8 encoding) RRS feed

  • Question

  • Want to generate a signature with sha256 with rsa2048(PKCS8) in .net, have private key pkcs8 format in string. Is there any library to do the same in .net ?

    In java found code online :

    import java.security.KeyFactory;
    import java.security.Signature;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.util.Base64;
    
    
    public class SignatureGenerator {
    	public static void main(String argsp[]) throws Exception {
    		String input = "{\"head\":\"SomeJsonData\"}";
    		//Private key in PKCS8 format which is incomplete 
            String strPk =  "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCp7r8szDlrBSaA\r\n";
             
            String base64Signature = signSHA256RSA(input,strPk);
            System.out.println("Signature="+base64Signature);
    	}
    	private static String signSHA256RSA(String input, String strPk) throws Exception {
            // Remove markers and new line characters in private key
            String realPK = strPk.replaceAll("-----END PRIVATE KEY-----", "")
                                 .replaceAll("-----BEGIN PRIVATE KEY-----", "")
                                 .replaceAll(" ","")
                                 .replaceAll("\r\n", "");
            String modifyInput = input.replaceAll("\r\n", "")
            						  .replaceAll(" ", "");
            System.out.println("Signature :" + realPK);
            System.out.println("Input String : "+ modifyInput);
            modifyInput = modifyInput.toString();
            byte[] b1 = Base64.getDecoder().decode(realPK);
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(b1);
            KeyFactory kf = KeyFactory.getInstance("RSA");
     
            Signature privateSignature = Signature.getInstance("SHA256withRSA");
            privateSignature.initSign(kf.generatePrivate(spec));
            privateSignature.update(modifyInput.getBytes("UTF-8"));
            byte[] s = privateSignature.sign();
            return Base64.getEncoder().encodeToString(s);
        }
    }

    • Edited by Puru1996 Friday, March 27, 2020 5:25 AM
    Friday, March 27, 2020 4:13 AM