I want sign a file using C#.Net and verify the file using Java. I am using SHA256withRSA algorithm for file sign process. I have a code both sign and verify using Java. But I need to convert file signing process to C#. I would be much grateful if somebody give me the guidance to resolve this matter.
File signing processing in Java
File file = new File(fileLocation);
signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey, new SecureRandom());
byte [] bytes;
try (InputStream is = new BufferedInputStream(new FileInputStream(file.getAbsolutePath()))) {
bytes = new byte[1024];
for (int read = 0; (read = is.read(bytes)) != -1;) {
signature.update(bytes,0,read);
}
}
byte[] signatureBytes = signature.sign();
byte[] signatureLength = ByteBuffer.allocate(4).putInt(signatureBytes.length).array();
byte[] version = ByteBuffer.allocate(4).putInt(1).array();
String writeLoc = outPutLocation + File.separator + "TEST_" + FilenameUtils.getName(fileLocation);
FileOutputStream outputStream = new FileOutputStream(new File(writeLoc));
outputStream.write(version);
outputStream.write(signatureLength);
outputStream.write(signatureBytes);
try (InputStream is = new BufferedInputStream(new FileInputStream(file.getAbsolutePath()))) {
bytes = new byte[1024];
for (int read = 0; (read = is.read(bytes)) != -1;) {
outputStream.write(bytes,0,read);
}
}
outputStream.close();
File verify process in Java
PublicKey publicKey = this.getPublicKey(stringKey);
this.signatureOne = Signature.getInstance("SHA256withRSA");
int signedDataLen = this.getSignatureLength(fileLocation);
if (signedDataLen == 256) {
byte[] signature = this.getSignatureBytes(fileLocation, signedDataLen);
if (publicKey != null) {
this.signatureOne.initVerify(publicKey);
if (this.signatureOne.verify(signature)) {
this.writeVerifiedFileToNewLocation(fileLocation, outPutLocation, signedDataLen);
return true;
} else {
return false;
}
} else {
return true;
}
} else {
return false;
}