title: How can I preform OpenSSL sign command in Java
body: <p>I have a private key given by my customer. I need to sign a binary data using RSA algorithm. The OpenSSL command which perfectly works for me is:</p>
  
  <pre><code>openssl.exe rsautl -in InputData.bin -inkey private.key -out OutputData.bin -sign
  </code></pre>
  
  <p>How can I implement such signature in Java? I don't need to use any hashing algorithm, and my given private key is a 768-bit key.</p>
  
  <p>I have written the following java code, but the signature created is not identical to the OutputData.bin file, and the verify method returns false. Can anyone help me identify what went wrong?</p>
  
  <pre><code>public static void main(String[] args) throws Exception {
  
  KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  
  //Read the input data
  byte[] data = readBytesfromFile("InputData.bin");
  
  //Read the private key file
  byte[] privateKeyBytes = readBytesfromFile("private.key");
  String strPrivateKey = new String(privateKeyBytes, "UTF-8").replaceAll("(-+BEGIN PRIVATE KEY-+\\r?\\n|-+END PRIVATE KEY-+\\r?\\n?)", "");
  PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(strPrivateKey));
  PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
  
  //Read the public key file
  byte[] publicKeyBytes = readBytesfromFile("public.key");
  String strPublicKey = new String(publicKeyBytes, "UTF-8").replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", "");
  X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(DatatypeConverter.parseBase64Binary(strPublicKey));
  PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
  
  //Sign the file
  Signature sig = Signature.getInstance("NONEwithRSA");
  sig.initSign(privateKey);
  sig.update(data);
  byte[] signatureBytes = sig.sign();
  
  //Verify the signature
  sig.initVerify(publicKey);
  sig.update(data);
  System.out.println(sig.verify(signatureBytes));
  }
  </code></pre>
  
  <p>I have double check, and the public key matches the private key. I have extracted the public key out of the private key.</p>
  
  <p>Any help will be highly appreciated.</p>
  
  <p>Thanks, Guy Hudara</p>