Java Code Examples for java.security.PublicKey#getAlgorithm()

The following examples show how to use java.security.PublicKey#getAlgorithm() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: V1SchemeSigner.java    From walle with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 2
Source File: Credentials.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 3
Source File: NewCertificateContract.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
   }
}
 
Example 4
Source File: DOMKeyInfoFactory.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 5
Source File: V2SchemeSigner.java    From walle with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 6
Source File: DOMKeyInfoFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 7
Source File: DOMKeyInfoFactory.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 8
Source File: DOMKeyInfoFactory.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 9
Source File: DOMKeyInfoFactory.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 10
Source File: DOMKeyInfoFactory.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 11
Source File: SM2X509CertMaker.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 12
Source File: NewCertificateContract.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
   }
}
 
Example 13
Source File: IaikP11Identity.java    From xipki with Apache License 2.0 5 votes vote down vote up
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() + ")");
  }
}
 
Example 14
Source File: NewCertificateContract.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
   }
}
 
Example 15
Source File: SimpleBatchSTSClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 16
Source File: DOMKeyInfoFactory.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 17
Source File: verifyFido2RegistrationPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
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());
    }
}
 
Example 18
Source File: ServiceLogger.java    From sftpserver with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example 19
Source File: ServiceLogger.java    From sftpserver with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example 20
Source File: CertificateMessage.java    From openjsse with GNU General Public License v2.0 4 votes vote down vote up
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);
    }
}