java.security.PublicKey Java Examples

The following examples show how to use java.security.PublicKey. 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: CertCrypto.java    From MaxKey with Apache License 2.0 7 votes vote down vote up
/**
 * <p>
 * 公钥解密
 * </p>
 * 
 * @param encryptedData 已加密数�?
 * @param certificatePath 证书存储路径
 * @return
 * @throws Exception
 */
public static byte[] decryptByPublicKey(byte[] encryptedData, Certificate certificate)
        throws Exception {
    PublicKey publicKey = KeyStoreUtil.getPublicKey(certificate);
    Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, publicKey);
    int inputLen = encryptedData.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int i = 0;
    // 对数据分段解�?
    while (inputLen - offSet > 0) {
        if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
            cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
        } else {
            cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
        }
        out.write(cache, 0, cache.length);
        i++;
        offSet = i * MAX_DECRYPT_BLOCK;
    }
    byte[] decryptedData = out.toByteArray();
    out.close();
    return decryptedData;
}
 
Example #2
Source File: GenerateKeyImpl.java    From julongchain with Apache License 2.0 6 votes vote down vote up
public PublicKey LoadPublicKeyAsPEM(String path,  String algorithm)
        throws IOException, NoSuchAlgorithmException,InvalidKeySpecException {

    File file = new File(path);
    InputStream inputStream = new FileInputStream(file);//文件内容的字节流
    InputStreamReader inputStreamReader= new InputStreamReader(inputStream); //得到文件的字符流
    BufferedReader bufferedReader=new BufferedReader(inputStreamReader); //放入读取缓冲区
    String readd="";
    StringBuffer stringBuffer=new StringBuffer();
    while ((readd=bufferedReader.readLine())!=null) {
        stringBuffer.append(readd);
    }
    inputStream.close();
    String content=stringBuffer.toString();

    String strPublicKey = content.replace("-----BEGIN PUBLIC KEY-----\n", "")
            .replace("-----END PUBLIC KEY-----", "").replace("\n", "");
    byte[] asBytes = Base64Utils.decode(strPublicKey.getBytes());
    X509EncodedKeySpec spec = new X509EncodedKeySpec(asBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    return keyFactory.generatePublic(spec);
}
 
Example #3
Source File: DHKeyFactory.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a public key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the public key
 *
 * @return the public key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a public key.
 */
protected PublicKey engineGeneratePublic(KeySpec keySpec)
    throws InvalidKeySpecException
{
    try {
        if (keySpec instanceof DHPublicKeySpec) {
            DHPublicKeySpec dhPubKeySpec = (DHPublicKeySpec)keySpec;
            return new DHPublicKey(dhPubKeySpec.getY(),
                                   dhPubKeySpec.getP(),
                                   dhPubKeySpec.getG());

        } else if (keySpec instanceof X509EncodedKeySpec) {
            return new DHPublicKey
                (((X509EncodedKeySpec)keySpec).getEncoded());

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification", e);
    }
}
 
Example #4
Source File: BasicChecker.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Internal method to create a new key with inherited key parameters.
 *
 * @param keyValueKey key from which to obtain key value
 * @param keyParamsKey key from which to obtain key parameters
 * @return new public key having value and parameters
 * @throws CertPathValidatorException if keys are not appropriate types
 * for this operation
 */
static PublicKey makeInheritedParamsKey(PublicKey keyValueKey,
    PublicKey keyParamsKey) throws CertPathValidatorException
{
    if (!(keyValueKey instanceof DSAPublicKey) ||
        !(keyParamsKey instanceof DSAPublicKey))
        throw new CertPathValidatorException("Input key is not " +
                                             "appropriate type for " +
                                             "inheriting parameters");
    DSAParams params = ((DSAPublicKey)keyParamsKey).getParams();
    if (params == null)
        throw new CertPathValidatorException("Key parameters missing");
    try {
        BigInteger y = ((DSAPublicKey)keyValueKey).getY();
        KeyFactory kf = KeyFactory.getInstance("DSA");
        DSAPublicKeySpec ks = new DSAPublicKeySpec(y,
                                                   params.getP(),
                                                   params.getQ(),
                                                   params.getG());
        return kf.generatePublic(ks);
    } catch (GeneralSecurityException e) {
        throw new CertPathValidatorException("Unable to generate key with" +
                                             " inherited parameters: " +
                                             e.getMessage(), e);
    }
}
 
Example #5
Source File: Crypto.java    From spark-setup-android with Apache License 2.0 6 votes vote down vote up
static PublicKey buildPublicKey(byte[] rawBytes) throws CryptoException {
    try {
        //FIXME replacing X509EncodedKeySpec because of problem with 8.1
        //Since 8.1 Bouncycastle cryptography was replaced with implementation from Conscrypt
        //https://developer.android.com/about/versions/oreo/android-8.1.html
        //either it's a bug in Conscrypt, our public key DER structure or use of X509EncodedKeySpec changed
        //alternative needed as this adds expensive Spongycastle dependence
        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(rawBytes));
        SubjectPublicKeyInfo info = SubjectPublicKeyInfo
                .getInstance(new ASN1InputStream(bIn.readObject().getEncoded()).readObject());
        DLSequence dlSequence = (DLSequence) ASN1Primitive.fromByteArray(info.getPublicKeyData().getBytes());
        BigInteger modulus = ((ASN1Integer) dlSequence.getObjectAt(0)).getPositiveValue();
        BigInteger exponent = ((ASN1Integer) dlSequence.getObjectAt(1)).getPositiveValue();

        RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
        KeyFactory kf = getRSAKeyFactory();
        return kf.generatePublic(spec);
    } catch (InvalidKeySpecException | IOException e) {
        throw new CryptoException(e);
    }
}
 
Example #6
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private String processHolderOfKeyCredentials(Credential hokCred, String request) throws TechnicalConnectorException, CertificateEncodingException {
   if (hokCred != null && hokCred.getCertificate() != null) {
      request = StringUtils.replace(request, "${holder.of.key}", new String(Base64.encode(hokCred.getCertificate().getEncoded())));
      PublicKey publicKey = hokCred.getCertificate().getPublicKey();
      if (publicKey instanceof RSAPublicKey) {
         RSAPublicKey rsaPublicKey = (RSAPublicKey)publicKey;
         request = StringUtils.replace(request, "${publickey.rsa.modulus}", new String(Base64.encode(convertTo(rsaPublicKey.getModulus()))));
         request = StringUtils.replace(request, "${publickey.rsa.exponent}", new String(Base64.encode(convertTo(rsaPublicKey.getPublicExponent()))));
         request = StringUtils.replace(request, "<ds:DSAKeyValue><ds:G>${publickey.dsa.g}<ds:G><ds:P>${publickey.dsa.p}</ds:P><ds:Q>${publickey.dsa.q}</ds:Q></ds:DSAKeyValue>", "");
      } else if (publicKey instanceof DSAPublicKey) {
         DSAPublicKey dsaPublicKey = (DSAPublicKey)publicKey;
         request = StringUtils.replace(request, "${publickey.dsa.g}", new String(Base64.encode(convertTo(dsaPublicKey.getParams().getG()))));
         request = StringUtils.replace(request, "${publickey.dsa.p}", new String(Base64.encode(convertTo(dsaPublicKey.getParams().getP()))));
         request = StringUtils.replace(request, "${publickey.dsa.q}", new String(Base64.encode(convertTo(dsaPublicKey.getParams().getQ()))));
         request = StringUtils.replace(request, "<ds:RSAKeyValue><ds:Modulus>${publickey.rsa.modulus}</ds:Modulus><ds:Exponent>${publickey.rsa.exponent}</ds:Exponent></ds:RSAKeyValue>", "");
      } else {
         LOG.info("Unsupported public key: [" + publicKey.getClass().getName() + "+]");
      }
   }

   return request;
}
 
Example #7
Source File: KeyInfoReferenceResolver.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc}. */
public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage)
    throws KeyResolverException {

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
    }

    if (!engineCanResolve(element, baseURI, storage)) {
        return null;
    }

    try {
        KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage);
        if (referent != null) {
            return referent.getPublicKey();
        }
    } catch (XMLSecurityException e) {
        if (log.isLoggable(java.util.logging.Level.FINE)) {
            log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
        }
    }

    return null;
}
 
Example #8
Source File: KeyManager.java    From Alpine with Apache License 2.0 6 votes vote down vote up
/**
 * Saves a key pair.
 *
 * @param keyPair the key pair to save
 * @throws IOException if the files cannot be written
 * @since 1.0.0
 */
public void save(final KeyPair keyPair) throws IOException {
    LOGGER.info("Saving key pair");
    final PrivateKey privateKey = keyPair.getPrivate();
    final PublicKey publicKey = keyPair.getPublic();

    // Store Public Key
    final File publicKeyFile = getKeyPath(publicKey);
    publicKeyFile.getParentFile().mkdirs(); // make directories if they do not exist
    final X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    try (OutputStream fos = Files.newOutputStream(publicKeyFile.toPath())) {
        fos.write(x509EncodedKeySpec.getEncoded());
    }

    // Store Private Key.
    final File privateKeyFile = getKeyPath(privateKey);
    privateKeyFile.getParentFile().mkdirs(); // make directories if they do not exist
    final PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    try (OutputStream fos = Files.newOutputStream(privateKeyFile.toPath())) {
        fos.write(pkcs8EncodedKeySpec.getEncoded());
    }
}
 
Example #9
Source File: PassportTransactionFormatter.java    From polling-station-app with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Signs the raw bytes using a travel document.
 * Follows the steps in this answer: https://bitcoin.stackexchange.com/a/5241
 * @return signedRawTransaction
 */
public byte[] signRawTransaction(PublicKey pubkey, byte[][] parts, PassportConnection pcon) throws Exception {
    byte[] rawTransaction = Bytes.concat(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5],
            parts[6], parts[7], parts[8], parts[9], parts[10], parts[11], parts[12]);

    // Double hash transaction
    byte[] step14 = Sha256Hash.hash(Sha256Hash.hash(rawTransaction));

    // Generate signature and get publickey
    byte[] multiSignature = new byte[320];
    byte[] hashPart;

    for (int i = 0; i < 4; i++) {
        hashPart = Arrays.copyOfRange(step14, i * 8, i * 8 + 8);
        System.arraycopy(pcon.signData(hashPart), 0, multiSignature, i * 80, 80);
    }

    byte[] signatureLength = Util.hexStringToByteArray("fd97014d4101");
    byte[] hashCodeType = Util.hexStringToByteArray("01");
    byte[] publicKeyASN = pubkey.getEncoded();

    byte[] publicKey = new byte[81];
    System.arraycopy(publicKeyASN, publicKeyASN.length-81, publicKey, 0, 81);

    byte[] publickeyLength = Util.hexStringToByteArray("4c51");

    // Set signature and pubkey in format
    byte[] step16 = Bytes.concat(signatureLength, multiSignature, hashCodeType, publickeyLength, publicKey);

    // Update transaction with signature and remove hash code type
    byte[] step19 = Bytes.concat(parts[0], parts[1], parts[2], parts[3], step16, parts[6],
            parts[7], parts[8], parts[9], parts[10], parts[11], parts[12]);

    return step19;
}
 
Example #10
Source File: RevocationChecker.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private void checkCRLs(X509Certificate cert,
                       Collection<String> unresolvedCritExts,
                       Set<X509Certificate> stackedCerts,
                       PublicKey pubKey, boolean signFlag)
    throws CertPathValidatorException
{
    checkCRLs(cert, pubKey, null, signFlag, true,
              stackedCerts, params.trustAnchors());
}
 
Example #11
Source File: RSAKeyValueResolver.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/** @inheritDoc */
public PublicKey engineLookupAndResolvePublicKey(
    Element element, String BaseURI, StorageResolver storage
) {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
    }
    if (element == null) {
        return null;
    }

    boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE);
    Element rsaKeyElement = null;
    if (isKeyValue) {
        rsaKeyElement =
            XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_RSAKEYVALUE, 0);
    } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RSAKEYVALUE)) {
        // this trick is needed to allow the RetrievalMethodResolver to eat a
        // ds:RSAKeyValue directly (without KeyValue)
        rsaKeyElement = element;
    }

    if (rsaKeyElement == null) {
        return null;
    }

    try {
        RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement, BaseURI);

        return rsaKeyValue.getPublicKey();
    } catch (XMLSecurityException ex) {
        if (log.isLoggable(java.util.logging.Level.FINE)) {
            log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
        }
    }

    return null;
}
 
Example #12
Source File: AlgorithmChecker.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check the signature algorithm with the specified public key.
 *
 * @param key the public key to verify the CRL signature
 * @param algorithmId signature algorithm Algorithm ID
 * @param variant is the Validator variants of the operation. A null value
 *                passed will set it to Validator.GENERIC.
 */
static void check(PublicKey key, AlgorithmId algorithmId, String variant)
                    throws CertPathValidatorException {
    String sigAlgName = algorithmId.getName();
    AlgorithmParameters sigAlgParams = algorithmId.getParameters();

    certPathDefaultConstraints.permits(new ConstraintsParameters(
            sigAlgName, sigAlgParams, key, variant));
}
 
Example #13
Source File: Security.java    From android-easy-checkout with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a PublicKey instance from a string containing the
 * Base64-encoded public key.
 *
 * @param encodedPublicKey rsa public key generated by Google Play Developer Console
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
protected PublicKey generatePublicKey(String encodedPublicKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException {

    byte[] decodedKey = Base64.decode(encodedPublicKey, Base64.DEFAULT);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
}
 
Example #14
Source File: DOMKeyInfoFactory.java    From openjdk-jdk8u 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 #15
Source File: CertificateKeyStoreFactory.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * create a {@link java.security.KeyStore} for this certificate
 * @param commonName  this field is only used for generating new identity certificate
 * @param sans a list of alternate subject names, that also will be used for generating identity certificate
 * @return keystore for this new certificate
 *
 * */
public KeyStore create(String commonName, List<ASN1Encodable> sans)
    throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, OperatorCreationException,
           NoSuchProviderException, InvalidKeyException, SignatureException {
  KeyPair keyPair = _keyPairFactory.create();
  PublicKey publicKey = keyPair.getPublic();
  PrivateKey privateKey = keyPair.getPrivate();
  X509Certificate identityCertificate =
      _certificateService.createSignedCertificate(publicKey, privateKey, commonName, sans);
  KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
  keyStore.load(null, null);

  _certificateService.updateKeyStore(keyStore, privateKey, identityCertificate);
  return keyStore;
}
 
Example #16
Source File: RSAKeyLoader.java    From library with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the public key of some processes from configuration files
 *
 * @return the PublicKey loaded from config/keys/publickey<id>
 * @throws Exception problems reading or parsing the key
 */
public PublicKey loadPublicKey(int id) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {

        if (defaultKeys) {
            return getPublicKeyFromString(RSAKeyLoader.DEFAULT_UKEY);
        }
        
        PublicKey ret = pubKeys.get(id);
        
        if (ret == null) {
            
            FileReader f = new FileReader(path + "publickey" + id);
            BufferedReader r = new BufferedReader(f);
            String tmp = "";
            String key = "";
            while ((tmp = r.readLine()) != null) {
                    key = key + tmp;
            }
            f.close();
            r.close();
            ret = getPublicKeyFromString(key);
            
            pubKeys.put(id, ret);
        }
        
        return ret;
}
 
Example #17
Source File: NetconfSessionMinaImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
private PublicKey getPublicKey(byte[] keyBytes, String type)
        throws NoSuchAlgorithmException, InvalidKeySpecException {

    X509EncodedKeySpec spec =
            new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance(type);
    return kf.generatePublic(spec);
}
 
Example #18
Source File: X509CertSelectorTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private void testSubjectPublicKey() throws IOException, GeneralSecurityException {
    System.out.println("X.509 Certificate Match on subject public key");
    // bad match
    X509CertSelector selector = new X509CertSelector();
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
            Base64.getMimeDecoder().decode(testKey.getBytes()));
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    PublicKey pubKey = keyFactory.generatePublic(keySpec);
    selector.setSubjectPublicKey(pubKey);
    checkMatch(selector, cert, false);

    // good match
    selector.setSubjectPublicKey(cert.getPublicKey());
    checkMatch(selector, cert, true);
}
 
Example #19
Source File: ElGamalTest2.java    From java_security with MIT License 5 votes vote down vote up
/**
 * 初始化密钥对
 * @return Map 甲方密钥的Map
 * */
public static Map<String,Object> initKey() throws Exception{
	//加入对BouncyCastle支持
	Security.addProvider(new BouncyCastleProvider());
	AlgorithmParameterGenerator apg=AlgorithmParameterGenerator.getInstance(KEY_ALGORITHM);
	//初始化参数生成器
	apg.init(KEY_SIZE);
	//生成算法参数
	AlgorithmParameters params=apg.generateParameters();
	//构建参数材料
	DHParameterSpec elParams=(DHParameterSpec)params.getParameterSpec(DHParameterSpec.class);
	
	//实例化密钥生成器
	KeyPairGenerator kpg=KeyPairGenerator.getInstance(KEY_ALGORITHM) ;
	
	//初始化密钥对生成器
	kpg.initialize(elParams,new SecureRandom());
	
	KeyPair keyPair=kpg.generateKeyPair();
	//甲方公钥
	PublicKey publicKey= keyPair.getPublic();
	//甲方私钥
	PrivateKey privateKey= keyPair.getPrivate();
	//将密钥存储在map中
	Map<String,Object> keyMap=new HashMap<String,Object>();
	keyMap.put(PUBLIC_KEY, publicKey);
	keyMap.put(PRIVATE_KEY, privateKey);
	return keyMap;
	
}
 
Example #20
Source File: AuthenticationTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test   // see SSHD-620
public void testHostBasedAuthentication() throws Exception {
    final String hostClienUser = getClass().getSimpleName();
    final String hostClientName = SshdSocketAddress.toAddressString(SshdSocketAddress.getFirstExternalNetwork4Address());
    final KeyPair hostClientKey = Utils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024);
    final AtomicInteger invocationCount = new AtomicInteger(0);
    sshd.setHostBasedAuthenticator(new HostBasedAuthenticator() {
        @Override
        public boolean authenticate(ServerSession session, String username,
                PublicKey clientHostKey, String clientHostName, String clientUsername, List<X509Certificate> certificates) {
            invocationCount.incrementAndGet();
            return hostClienUser.equals(clientUsername)
                && hostClientName.equals(clientHostName)
                && KeyUtils.compareKeys(hostClientKey.getPublic(), clientHostKey);
        }
    });
    sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE);
    sshd.setKeyboardInteractiveAuthenticator(KeyboardInteractiveAuthenticator.NONE);
    sshd.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE);
    sshd.setUserAuthFactories(
            Collections.<NamedFactory<org.apache.sshd.server.auth.UserAuth>>singletonList(
                    org.apache.sshd.server.auth.hostbased.UserAuthHostBasedFactory.INSTANCE));

    try (SshClient client = setupTestClient()) {
        org.apache.sshd.client.auth.hostbased.UserAuthHostBasedFactory factory =
                new org.apache.sshd.client.auth.hostbased.UserAuthHostBasedFactory();
        // TODO factory.setClientHostname(CLIENT_HOSTNAME);
        factory.setClientUsername(hostClienUser);
        factory.setClientHostKeys(HostKeyIdentityProvider.Utils.wrap(hostClientKey));

        client.setUserAuthFactories(Collections.<NamedFactory<org.apache.sshd.client.auth.UserAuth>>singletonList(factory));
        client.start();
        try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            s.auth().verify(11L, TimeUnit.SECONDS);
            assertEquals("Mismatched authenticator invocation count", 1, invocationCount.get());
        } finally {
            client.stop();
        }
    }
}
 
Example #21
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 5 votes vote down vote up
/**
 * convert a base64 encoded certificate into a java object public key
 */
public static PublicKey makePublicKey(final String certificateBase64) {

    if (certificateBase64 == null || certificateBase64.isEmpty()) {
        throw new IllegalArgumentException("Supplied 'certificateBase64' argument is null or empty.");
    }

    try {
        final CertificateFactory cf = CertificateFactory.getInstance(PUBLIC_CERT_ALGORITHM);
        final Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(Base64.decode(certificateBase64)));
        return certificate.getPublicKey();
    } catch (final CertificateException e) {
        throw new RuntimeException("Unable to generate certificates (" + PUBLIC_CERT_ALGORITHM + ") " + e.getMessage(), e);
    } 
}
 
Example #22
Source File: KeyDef.java    From swim with Apache License 2.0 5 votes vote down vote up
public static KeyDef from(Key key) {
  if (key instanceof PublicKey) {
    return PublicKeyDef.from((PublicKey) key);
  } else if (key instanceof PrivateKey) {
    return PrivateKeyDef.from((PrivateKey) key);
  }
  throw new IllegalArgumentException(key.toString());
}
 
Example #23
Source File: Offsets.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static Offsets init(String provider, String algorithm)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeyException, SignatureException {
    // fill the cleartext data with random bytes
    byte[] cleartext = new byte[100];
    RandomFactory.getRandom().nextBytes(cleartext);

    // NONEwith requires input to be of 20 bytes
    int size = algorithm.contains("NONEwith") ? 20 : 100;

    // create signature instance
    Signature signature = Signature.getInstance(algorithm, provider);

    String keyAlgo;
    if (algorithm.contains("RSA")) {
        keyAlgo = "RSA";
    } else if (algorithm.contains("ECDSA")) {
        keyAlgo = "EC";
    } else if (algorithm.contains("DSA")) {
        keyAlgo = "DSA";
    } else {
        throw new RuntimeException("Test doesn't support this signature "
                + "algorithm: " + algorithm);
    }

    KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo, provider);
    KeyPair kp = kpg.generateKeyPair();
    PublicKey pubkey = kp.getPublic();
    PrivateKey privkey = kp.getPrivate();

    return new Offsets(signature, pubkey, privkey, size, cleartext);
}
 
Example #24
Source File: SamlUtils.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
public static String signSamlResponse(final String samlResponse,
        final PrivateKey privateKey, final PublicKey publicKey) {
    final Document doc = constructDocumentFromXmlString(samlResponse);

    if (doc != null) {
        final Element signedElement = signSamlElement(doc.getRootElement(),
                privateKey, publicKey);
        doc.setRootElement((Element) signedElement.detach());
        return new XMLOutputter().outputString(doc);
    }
    throw new RuntimeException("Error signing SAML Response: Null document");
}
 
Example #25
Source File: CertId.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public CertId(X500Principal issuerName, PublicKey issuerKey,
              SerialNumber serialNumber) throws IOException {

    // compute issuerNameHash
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA1");
    } catch (NoSuchAlgorithmException nsae) {
        throw new IOException("Unable to create CertId", nsae);
    }
    hashAlgId = SHA1_ALGID;
    md.update(issuerName.getEncoded());
    issuerNameHash = md.digest();

    // compute issuerKeyHash (remove the tag and length)
    byte[] pubKey = issuerKey.getEncoded();
    DerValue val = new DerValue(pubKey);
    DerValue[] seq = new DerValue[2];
    seq[0] = val.data.getDerValue(); // AlgorithmID
    seq[1] = val.data.getDerValue(); // Key
    byte[] keyBytes = seq[1].getBitString();
    md.update(keyBytes);
    issuerKeyHash = md.digest();
    certSerialNumber = serialNumber;

    if (debug) {
        HexDumpEncoder encoder = new HexDumpEncoder();
        System.out.println("Issuer Name is " + issuerName);
        System.out.println("issuerNameHash is " +
            encoder.encodeBuffer(issuerNameHash));
        System.out.println("issuerKeyHash is " +
            encoder.encodeBuffer(issuerKeyHash));
        System.out.println("SerialNumber is " + serialNumber.getNumber());
    }
}
 
Example #26
Source File: DOMKeyValue.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public PublicKey getPublicKey() throws KeyException {
    if (publicKey == null) {
        throw new KeyException("can't convert KeyValue to PublicKey");
    } else {
        return publicKey;
    }
}
 
Example #27
Source File: PluginManager.java    From WorldPainter with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings({"StatementWithEmptyBody", "BooleanMethodIsAlwaysInverted"})
private static boolean isSigned(JarFile jarFile, PublicKey publicKey) throws IOException {
    for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements(); ) {
        // Iterator over all the entries in the jar except directories and
        // signature files
        JarEntry jarEntry = e.nextElement();
        String entryName = jarEntry.getName().toUpperCase();
        if (jarEntry.isDirectory() || entryName.endsWith(".SF") || entryName.endsWith(".DSA") || entryName.endsWith(".EC") || entryName.endsWith(".RSA")) {
            continue;
        }

        // Read the entry fully, otherwise the certificates won't be available
        byte[] buffer = new byte[BUFFER_SIZE];
        try (InputStream in = jarFile.getInputStream(jarEntry)) {
            while (in.read(buffer) != -1) ;
        }

        // Get the signing certificate chain and check if one of them is the
        // WorldPainter plugin signing certificate
        Certificate[] certificates = jarEntry.getCertificates();
        boolean signed = false;
        if (certificates != null) {
            for (Certificate certificate: certificates) {
                if (certificate.getPublicKey().equals(publicKey)) {
                    signed = true;
                    break;
                }
            }
        }
        if (! signed) {
            return false;
        }
    }
    return true;
}
 
Example #28
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private PublicKey getRevocationPublicKey(String str) throws EnrollmentException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (Utils.isNullOrEmpty(str)) {
        throw new EnrollmentException("fabric-ca-server did not return 'issuerPublicKey' in the response from " + HFCA_IDEMIXCRED);
    }
    String pem = new String(Base64.getDecoder().decode(str));
    byte[] der = convertPemToDer(pem);
    return KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(der));
}
 
Example #29
Source File: GoogleRSAKeyProvider.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private RSAPublicKey safelyCastToRsaPublicKey(PublicKey publicKey) {
  if (publicKey instanceof RSAPublicKey) {
    return (RSAPublicKey) publicKey;
  } else {
    throw new AlgorithmMismatchException("We expected RSAPublicKey from certificate");
  }
}
 
Example #30
Source File: KeyFactorySpi.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
protected PublicKey engineGeneratePublic(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof ElGamalPublicKeySpec)
    {
        return new BCElGamalPublicKey((ElGamalPublicKeySpec)keySpec);
    }
    else if (keySpec instanceof DHPublicKeySpec)
    {
        return new BCElGamalPublicKey((DHPublicKeySpec)keySpec);
    }
    return super.engineGeneratePublic(keySpec);
}