blob: 13bc140d797d3504af138ee81248cf99bba0eb80 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
/**
* Misc signature utils
*
* @author bjorncs
*/
public class SignatureUtils {
/** Returns a signature instance which computes a hash of its content, before signing with the given private key. */
public static Signature createSigner(PrivateKey key, SignatureAlgorithm algorithm) {
try {
Signature signer = Signature.getInstance(algorithm.getAlgorithmName(), BouncyCastleProviderHolder.getInstance());
signer.initSign(key);
return signer;
} catch (GeneralSecurityException e) {
throw new IllegalStateException(e);
}
}
/** Returns a signature instance which computes a hash of its content, before signing with the given private key. */
public static Signature createSigner(PrivateKey key) {
return createSigner(key, getSignatureAlgorithm(key));
}
/** Returns a signature instance which computes a hash of its content, before verifying with the given public key. */
public static Signature createVerifier(PublicKey key, SignatureAlgorithm algorithm) {
try {
Signature signer = Signature.getInstance(algorithm.getAlgorithmName(), BouncyCastleProviderHolder.getInstance());
signer.initVerify(key);
return signer;
} catch (GeneralSecurityException e) {
throw new IllegalStateException(e);
}
}
/** Returns a signature instance which computes a hash of its content, before verifying with the given public key. */
public static Signature createVerifier(PublicKey key) {
return createVerifier(key, getSignatureAlgorithm(key));
}
/* Returns a signature algorithm supported by the key based on SHA512 */
private static SignatureAlgorithm getSignatureAlgorithm(Key key) {
switch (key.getAlgorithm()) {
case "EC":
return SignatureAlgorithm.SHA512_WITH_ECDSA;
case "RSA":
return SignatureAlgorithm.SHA512_WITH_RSA;
default:
throw new RuntimeException("Unknown Key algorithm " + key.getAlgorithm());
}
}
}
|