CryptoBase implements Crypto { public static String sign(String message, PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { Signature sign = Signature.getInstance(DIGEST_ALGORITHM); sign.initSign(privateKey); sign.update(message.getBytes()); return new String(Base64.encode(sign.sign(), Base64.DEFAULT)); }  @Override String getPublicKeyBase64Str(); static String sign(String message, PrivateKey privateKey); @Override String sign(String message);  }
@Test public void sign_shouldReturnSameSignOnTwoIdenticalCalls() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { PrivateKey privateKey = generatePrivateKey(); String signA = CryptoBase.sign("my_message", privateKey); String signB = CryptoBase.sign("my_message", privateKey); assertThat(signA) .isNotEmpty() .isEqualTo(signB); }
@Test public void sign_shouldReturnDifferentSignWhenProvidedWithDifferentMessages() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { PrivateKey privateKey = generatePrivateKey(); String signA = CryptoBase.sign("my_message_A", privateKey); String signB = CryptoBase.sign("my_message_B", privateKey); assertThat(signA) .isNotEmpty() .isNotEqualTo(signB); assertThat(signB).isNotEmpty(); }
@Test public void sign_shouldReturnDifferentSignWhenProvidedWithDifferentPrivateKeys() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { String signA = CryptoBase.sign("my_message", generatePrivateKey()); String signB = CryptoBase.sign("my_message", generatePrivateKey()); assertThat(signA) .isNotEmpty() .isNotEqualTo(signB); assertThat(signB).isNotEmpty(); }
@Test public void sign_shouldCaclculateAValidSignature() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, InvalidKeySpecException { PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decode("MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAskcFcO+vuYAQfRjCGkhZXMGlrtpbJZRq9y0SJi2DlKo2Ph58Ni9j6mN4DVKdSSJhuR/myNzXmszLzZIgq1AwpQIDAQABAkA641rYw1O4YqUPrW3wYJWkHhMsftQ8xZnPrAOiuMYOBN5jJ1pKBXiy3nHxBCiSWAJY+kWSWzbY1zzecBtmbCDBAiEA1lrU0Uhk3H7v7qyZPWIgu2pHYi+/W17c3jsl/NgHQfMCIQDU6dea1HCfWcU31cW/wShhzXd4h1H6AqEmRIEGnCLRBwIhAINNAC9x+NZXqwC4GOXQxdwHLdKnDMAbS4+VC5/ldAyhAiEAs4/PhMWbgdisyi0gzFpz2x/0nRLK4SXskKB/jHqLpmsCICTcahC8Xm8EFD/kxkDpI2oMZuWa2ghvZ1zuSMpnfkgE", Base64.DEFAULT)); KeyFactory keyFact = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFact.generatePrivate(pkcs8EncodedKeySpec); assertThat(CryptoBase.sign("my_data", privateKey)).isEqualTo("n8PEnZ5s5Cn39Jx2nMRf+cTbw7YIw5ak0HBEQJUl4mX/rMjo1SQe/56elt95c5H9TydbEcmvDeDt\n2SpHXylNDA==\n"); }