com.nimbusds.jose.jwk.loader.PKCS11ProviderConfigurationLoader Maven / Gradle / Ivy
Show all versions of nimbus-jwkset-loader Show documentation
package com.nimbusds.jose.jwk.loader;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import com.nimbusds.jose.util.Base64URL;
/**
* PKCS#11 JCA provider configuration loader.
*/
class PKCS11ProviderConfigurationLoader {
/**
* Loads a PKCS#11 provider configuration.
*
* See https://docs.oracle.com/en/java/javase/11/security/pkcs11-reference-guide1.html#GUID-C4ABFACB-B2C9-4E71-A313-79F881488BB9
*
* @param pkcs11ConfigSpec The PKCS#11 provider configuration, as file
* name or inline (with optional additional
* BASE64URL encoding). Must not be
* {@code null}.
* @param fisSource The file input stream source. Must not be
* {@code null}.
*
* @return The PKCS#11 JCA provider configuration.
*/
static String load(final String pkcs11ConfigSpec,
final FileInputStreamSource fisSource) {
InputStream is = fisSource.getInputSteam(pkcs11ConfigSpec);
final String inlineConfig;
if (is != null) {
inlineConfig = new BufferedReader(new InputStreamReader(is)).lines().collect(Collectors.joining("\n"));
} else if (isLikelyInlineConfig(pkcs11ConfigSpec)) {
inlineConfig = pkcs11ConfigSpec;
} else {
// BASE64URL encoded config
inlineConfig = new Base64URL(pkcs11ConfigSpec).decodeToString();
}
// https://stackoverflow.com/questions/46521791/sunpkcs11-provider-in-java-9
return "--" + inlineConfig;
}
/**
* Returns {@code true} if the string is likely an inline PKCS#11
* config and not a file name.
*
* @param s The string. Must not be {@code null}.
*
* @return {@code true} if likely an inline config, else {@code false}.
*/
static boolean isLikelyInlineConfig(final String s) {
return s.contains("\n")
|| s.contains("{")
|| s.contains("}")
|| s.contains("(")
|| s.contains(")")
|| s.contains("*")
|| s.trim().contains(" ");
}
}