下面列出了java.security.PublicKey#getAlgorithm ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static String getJcaSignatureAlgorithm(
PublicKey publicKey, DigestAlgorithm digestAlgorithm) throws InvalidKeyException {
String keyAlgorithm = publicKey.getAlgorithm();
String digestPrefixForSigAlg;
switch (digestAlgorithm) {
case SHA1:
digestPrefixForSigAlg = "SHA1";
break;
case SHA256:
digestPrefixForSigAlg = "SHA256";
break;
default:
throw new IllegalArgumentException(
"Unexpected digest algorithm: " + digestAlgorithm);
}
if ("RSA".equalsIgnoreCase(keyAlgorithm)) {
return digestPrefixForSigAlg + "withRSA";
} else if ("DSA".equalsIgnoreCase(keyAlgorithm)) {
return digestPrefixForSigAlg + "withDSA";
} else if ("EC".equalsIgnoreCase(keyAlgorithm)) {
return digestPrefixForSigAlg + "withECDSA";
} else {
throw new InvalidKeyException("Unsupported key algorithm: " + keyAlgorithm);
}
}
/**
* Creates new encrypted credentials
* <p>
* Encrypts the message '<code>credData</code>' using the
* public key <code>pubKey</code> and <code>cipher</code>
* and store it in a new Credentials object.
*
* @see KeyPairUtil#encrypt(PublicKey, String, byte[])
* @param cc, the class containing the data to be crypted
* @param pubKey public key used for encryption
* @param cipher cipher parameters: combination of transformations
* @return the Credentials object containing the encrypted data
* @throws KeyException key generation or encryption failed
*/
public static Credentials createCredentials(final CredData cc, final PublicKey pubKey, final String cipher)
throws KeyException {
// serialize clear credentials to byte array
byte[] clearCred;
try {
clearCred = ObjectToByteConverter.ObjectStream.convert(cc);
} catch (IOException e1) {
throw new KeyException(e1.getMessage());
}
HybridEncryptionUtil.HybridEncryptedData encryptedData = HybridEncryptionUtil.encrypt(pubKey,
cipher,
clearCred);
byte[] encAes = encryptedData.getEncryptedSymmetricKey();
byte[] encData = encryptedData.getEncryptedData();
int size = keySize(pubKey);
return new Credentials(pubKey.getAlgorithm(), size, cipher, encAes, encData);
}
public KeyValue newKeyValue(PublicKey key) throws KeyException {
String algorithm = key.getAlgorithm();
if (algorithm.equals("DSA")) {
return new DOMKeyValue.DSA(key);
} else if (algorithm.equals("RSA")) {
return new DOMKeyValue.RSA(key);
} else if (algorithm.equals("EC")) {
return new DOMKeyValue.EC(key);
} else {
throw new KeyException("unsupported key algorithm: " + algorithm);
}
}
protected void writeElementsForRSTPublicKey(W3CDOMStreamWriter writer,
X509Certificate cert) throws Exception {
writer.writeStartElement("wst", "UseKey", namespace);
writer.writeStartElement("dsig", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
writer.writeNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#");
boolean useCert = useCertificateForConfirmationKeyInfo;
String useCertStr = (String)getProperty(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO);
if (useCertStr != null) {
useCert = Boolean.parseBoolean(useCertStr);
}
if (useCert) {
X509Data certElem = new X509Data(writer.getDocument());
certElem.addCertificate(cert);
writer.getCurrentNode().appendChild(certElem.getElement());
} else {
writer.writeStartElement("dsig", "KeyValue", "http://www.w3.org/2000/09/xmldsig#");
PublicKey key = cert.getPublicKey();
String pubKeyAlgo = key.getAlgorithm();
if ("DSA".equalsIgnoreCase(pubKeyAlgo)) {
DSAKeyValue dsaKeyValue = new DSAKeyValue(writer.getDocument(), key);
writer.getCurrentNode().appendChild(dsaKeyValue.getElement());
} else if ("RSA".equalsIgnoreCase(pubKeyAlgo)) {
RSAKeyValue rsaKeyValue = new RSAKeyValue(writer.getDocument(), key);
writer.getCurrentNode().appendChild(rsaKeyValue.getElement());
}
writer.writeEndElement();
}
writer.writeEndElement();
writer.writeEndElement();
}
private int getKeySize(SubjectPublicKeyInfo subjectPKInfo) {
try {
X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes());
AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
String algorithm = publicKey.getAlgorithm();
KeyFactory keyFact = KeyFactory.getInstance(algorithm);
RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class);
BigInteger modulus = keySpec.getModulus();
return modulus.toString(2).length();
} catch (Exception var9) {
throw new IllegalArgumentException(var9);
}
}
IaikP11Identity(IaikP11Slot slot, P11IdentityId identityId, PrivateKey privateKey,
PublicKey publicKey, X509Cert[] certificateChain) {
super(slot, identityId, publicKey, certificateChain);
this.signingKey = Args.notNull(privateKey, "privateKey");
int keyBitLen = getSignatureKeyBitLength();
if (publicKey instanceof RSAPublicKey) {
expectedSignatureLen = (keyBitLen + 7) / 8;
} else if (publicKey instanceof ECPublicKey) {
expectedSignatureLen = (keyBitLen + 7) / 8 * 2;
} else if (publicKey instanceof DSAPublicKey) {
expectedSignatureLen = (keyBitLen + 7) / 8 * 2;
} else if (publicKey instanceof EdDSAKey) {
String algName = publicKey.getAlgorithm();
if (EdECConstants.ED25519.equalsIgnoreCase(algName)) {
expectedSignatureLen = 64;
} else if (EdECConstants.ED25519.equalsIgnoreCase(algName)) {
expectedSignatureLen = 114;
} else {
throw new IllegalArgumentException("unknown EdDSA algorithm " + algName);
}
} else if (publicKey instanceof XDHKey) {
// no signature is supported
expectedSignatureLen = 0;
} else {
throw new IllegalArgumentException(
"currently only RSA, DSA, EC, EdDSA and XDH public key are supported,"
+ " but not " + this.publicKey.getAlgorithm()
+ " (class: " + publicKey.getClass().getName() + ")");
}
}
private static int getKeySize(SubjectPublicKeyInfo subjectPKInfo) {
try {
X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes());
AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
String algorithm = publicKey.getAlgorithm();
KeyFactory keyFact = KeyFactory.getInstance(algorithm);
RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class);
BigInteger modulus = keySpec.getModulus();
return modulus.toString(2).length();
} catch (Exception var8) {
throw new IllegalArgumentException(var8);
}
}
private int getKeySize(SubjectPublicKeyInfo subjectPKInfo) {
try {
X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes());
AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
String algorithm = publicKey.getAlgorithm();
KeyFactory keyFact = KeyFactory.getInstance(algorithm);
RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class);
BigInteger modulus = keySpec.getModulus();
return modulus.toString(2).length();
} catch (Exception var9) {
throw new IllegalArgumentException(var9);
}
}
private JcaContentSignerBuilder makeContentSignerBuilder(PublicKey issPub) throws Exception {
if (issPub.getAlgorithm().equals("EC")) {
JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(SIGN_ALGO_SM3WITHSM2);
contentSignerBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME);
return contentSignerBuilder;
}
throw new Exception("Unsupported PublicKey Algorithm:" + issPub.getAlgorithm());
}
public KeyValue newKeyValue(PublicKey key) throws KeyException {
String algorithm = key.getAlgorithm();
if (algorithm.equals("DSA")) {
return new DOMKeyValue.DSA(key);
} else if (algorithm.equals("RSA")) {
return new DOMKeyValue.RSA(key);
} else if (algorithm.equals("EC")) {
return new DOMKeyValue.EC(key);
} else {
throw new KeyException("unsupported key algorithm: " + algorithm);
}
}
public KeyValue newKeyValue(PublicKey key) throws KeyException {
String algorithm = key.getAlgorithm();
if (algorithm.equals("DSA")) {
return new DOMKeyValue.DSA(key);
} else if (algorithm.equals("RSA")) {
return new DOMKeyValue.RSA(key);
} else if (algorithm.equals("EC")) {
return new DOMKeyValue.EC(key);
} else {
throw new KeyException("unsupported key algorithm: " + algorithm);
}
}
public KeyValue newKeyValue(PublicKey key) throws KeyException {
String algorithm = key.getAlgorithm();
if (algorithm.equals("DSA")) {
return new DOMKeyValue.DSA(key);
} else if (algorithm.equals("RSA")) {
return new DOMKeyValue.RSA(key);
} else if (algorithm.equals("EC")) {
return new DOMKeyValue.EC(key);
} else {
throw new KeyException("unsupported key algorithm: " + algorithm);
}
}
public KeyValue newKeyValue(PublicKey key) throws KeyException {
String algorithm = key.getAlgorithm();
if (algorithm.equals("DSA")) {
return new DOMKeyValue.DSA(key);
} else if (algorithm.equals("RSA")) {
return new DOMKeyValue.RSA(key);
} else if (algorithm.equals("EC")) {
return new DOMKeyValue.EC(key);
} else {
throw new KeyException("unsupported key algorithm: " + algorithm);
}
}
public KeyValue newKeyValue(PublicKey key) throws KeyException {
String algorithm = key.getAlgorithm();
if (algorithm.equals("DSA")) {
return new DOMKeyValue.DSA(key);
} else if (algorithm.equals("RSA")) {
return new DOMKeyValue.RSA(key);
} else if (algorithm.equals("EC")) {
return new DOMKeyValue.EC(key);
} else {
throw new KeyException("unsupported key algorithm: " + algorithm);
}
}
/**
* Gets the APK Signature Scheme v2 signature algorithms to be used for signing an APK using the
* provided key.
*
* @param minSdkVersion minimum API Level of the platform on which the APK may be installed (see
* AndroidManifest.xml minSdkVersion attribute).
*
* @throws InvalidKeyException if the provided key is not suitable for signing APKs using
* APK Signature Scheme v2
*/
public static List<SignatureAlgorithm> getSuggestedSignatureAlgorithms(
PublicKey signingKey, int minSdkVersion) throws InvalidKeyException {
String keyAlgorithm = signingKey.getAlgorithm();
if ("RSA".equalsIgnoreCase(keyAlgorithm)) {
// Use RSASSA-PKCS1-v1_5 signature scheme instead of RSASSA-PSS to guarantee
// deterministic signatures which make life easier for OTA updates (fewer files
// changed when deterministic signature schemes are used).
// Pick a digest which is no weaker than the key.
int modulusLengthBits = ((RSAKey) signingKey).getModulus().bitLength();
if (modulusLengthBits <= 3072) {
// 3072-bit RSA is roughly 128-bit strong, meaning SHA-256 is a good fit.
return Collections.singletonList(SignatureAlgorithm.RSA_PKCS1_V1_5_WITH_SHA256);
} else {
// Keys longer than 3072 bit need to be paired with a stronger digest to avoid the
// digest being the weak link. SHA-512 is the next strongest supported digest.
return Collections.singletonList(SignatureAlgorithm.RSA_PKCS1_V1_5_WITH_SHA512);
}
} else if ("DSA".equalsIgnoreCase(keyAlgorithm)) {
// DSA is supported only with SHA-256.
return Collections.singletonList(SignatureAlgorithm.DSA_WITH_SHA256);
} else if ("EC".equalsIgnoreCase(keyAlgorithm)) {
// Pick a digest which is no weaker than the key.
int keySizeBits = ((ECKey) signingKey).getParams().getOrder().bitLength();
if (keySizeBits <= 256) {
// 256-bit Elliptic Curve is roughly 128-bit strong, meaning SHA-256 is a good fit.
return Collections.singletonList(SignatureAlgorithm.ECDSA_WITH_SHA256);
} else {
// Keys longer than 256 bit need to be paired with a stronger digest to avoid the
// digest being the weak link. SHA-512 is the next strongest supported digest.
return Collections.singletonList(SignatureAlgorithm.ECDSA_WITH_SHA512);
}
} else {
throw new InvalidKeyException("Unsupported key algorithm: " + keyAlgorithm);
}
}
public KeyValue newKeyValue(PublicKey key) throws KeyException {
String algorithm = key.getAlgorithm();
if (algorithm.equals("DSA")) {
return new DOMKeyValue.DSA(key);
} else if (algorithm.equals("RSA")) {
return new DOMKeyValue.RSA(key);
} else if (algorithm.equals("EC")) {
return new DOMKeyValue.EC(key);
} else {
throw new KeyException("unsupported key algorithm: " + algorithm);
}
}
private void verifyCryptographyOptions(CryptographyPolicyOptions cryptoOp, JsonObject clientJson,
FIDO2AttestationObject attObject, Integer version) throws SKFEException {
ArrayList<String> allowedRSASignatures = cryptoOp.getAllowedRSASignatures();
ArrayList<String> allowedECSignatures = cryptoOp.getAllowedECSignatures();
ArrayList<String> supportedCurves = cryptoOp.getSupportedEllipticCurves();
ArrayList<String> allowedAttestationFormats = cryptoOp.getAllowedAttestationFormats();
ArrayList<String> allowedAttestationTypes = cryptoOp.getAllowedAttestationTypes();
//Verify attestation key
ArrayList certificateChain = attObject.getAttStmt().getX5c();
if(certificateChain != null){
X509Certificate attestationCert = cryptoCommon.generateX509FromBytes((byte[]) certificateChain.get(0));
if(attestationCert == null){
throw new SKFEException("Failed to parse X509Certificate. Check logs for details");
}
PublicKey attestationKey = attestationCert.getPublicKey();
String attestationAlgType = attestationKey.getAlgorithm();
if(!attestationAlgType.equalsIgnoreCase("RSA") && !attestationAlgType.equalsIgnoreCase("EC")){
throw new SKFEException("Unknown key algorithm (Attestation)");
}
if((allowedRSASignatures == null
|| !allowedRSASignatures.contains(skfsCommon.getPolicyAlgFromAlg(attestationCert.getSigAlgName())))
&& (allowedECSignatures == null
|| !allowedECSignatures.contains(skfsCommon.getPolicyAlgFromAlg(attestationCert.getSigAlgName())))){
throw new SKFEException("Signature Algorithm not supported by policy (Attestation): " + attestationCert.getSigAlgName());
}
//Verify that the curve used by the attestation key is approved
if(attestationAlgType.equalsIgnoreCase("EC")){
byte[] enc = attestationKey.getEncoded();
SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(enc));
AlgorithmIdentifier algid = spki.getAlgorithm();
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) algid.getParameters();
if(!supportedCurves.contains(skfsCommon.getPolicyCurveFromOID(oid))){
throw new SKFEException("EC Curve not supported by policy (Attestation)");
}
}
}
//Verify signing key
PublicKey signingKey = attObject.getAuthData().getAttCredData().getPublicKey();
String signingAlgType = signingKey.getAlgorithm();
if(!signingAlgType.equalsIgnoreCase("RSA") && !signingAlgType.equalsIgnoreCase("EC")){
throw new SKFEException("Unknown attestation key algorithm (Signing)");
}
if((allowedRSASignatures == null
|| !allowedRSASignatures.contains(skfsCommon.getPolicyAlgFromIANACOSEAlg(attObject.getAuthData().getAttCredData().getFko().getAlg())))
&& (allowedECSignatures == null
||!allowedECSignatures.contains(skfsCommon.getPolicyAlgFromIANACOSEAlg(attObject.getAuthData().getAttCredData().getFko().getAlg())))){
throw new SKFEException("Rejected key algorithm (Signing): " +
skfsCommon.getPolicyAlgFromIANACOSEAlg(attObject.getAuthData().getAttCredData().getFko().getAlg()));
}
if(signingAlgType.equalsIgnoreCase("EC")){
ECKeyObject eckey = (ECKeyObject) attObject.getAuthData().getAttCredData().getFko();
if(!supportedCurves.contains(skfsCommon.getPolicyCurveFromFIDOECCCurveID(eckey.getCrv()))){
throw new SKFEException("EC Curve not supported by policy (Signing)");
}
}
//Verify allowed AttestationFormat
if(!allowedAttestationFormats.contains(attObject.getAttFormat())){
throw new SKFEException("Attestation format not supported by policy: " + attObject.getAttFormat());
}
//Verify allowed AttestationType
if (!allowedAttestationTypes.contains(attObject.getAttStmt().getAttestationType())) {
throw new SKFEException("Attestation type not supported by policy: " + attObject.getAttStmt().getAttestationType());
}
}
private static void checkClientCerts(ServerHandshakeContext shc,
X509Certificate[] certs) throws IOException {
X509TrustManager tm = shc.sslContext.getX509TrustManager();
// find out the types of client authentication used
PublicKey key = certs[0].getPublicKey();
String keyAlgorithm = key.getAlgorithm();
String authType;
switch (keyAlgorithm) {
case "RSA":
case "DSA":
case "EC":
case "RSASSA-PSS":
authType = keyAlgorithm;
break;
default:
// unknown public key type
authType = "UNKNOWN";
}
try {
if (tm instanceof X509ExtendedTrustManager) {
if (shc.conContext.transport instanceof SSLEngine) {
SSLEngine engine = (SSLEngine)shc.conContext.transport;
((X509ExtendedTrustManager)tm).checkClientTrusted(
certs.clone(),
authType,
engine);
} else {
SSLSocket socket = (SSLSocket)shc.conContext.transport;
((X509ExtendedTrustManager)tm).checkClientTrusted(
certs.clone(),
authType,
socket);
}
} else {
// Unlikely to happen, because we have wrapped the old
// X509TrustManager with the new X509ExtendedTrustManager.
throw new CertificateException(
"Improper X509TrustManager implementation");
}
} catch (CertificateException ce) {
throw shc.conContext.fatal(Alert.CERTIFICATE_UNKNOWN, ce);
}
}
public void authPublicKeyPreLogin(final ServerSession session, final String username, final PublicKey key) {
final String keyType = (key == null ? "<unknown>" : key.getAlgorithm());
log.info("auth publickey(" + toHuman(session, username) + ") type: " + keyType);
}
public void authPublicKeyPostLogin(final ServerSession session, final String username, final PublicKey key,
final Level level, final String info) {
final String keyType = (key == null ? "<unknown>" : key.getAlgorithm());
logLevel("auth publickey(" + toHuman(session, username) + ") type: " + keyType //
+ " info: " + info, level);
}