Java Code Examples for java.security.PublicKey

The following examples show how to use java.security.PublicKey. These examples are extracted from open source projects. 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 Project: MaxKey   Source File: CertCrypto.java    License: 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 Project: jdk8u-jdk   Source File: DHKeyFactory.java    License: 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 3
Source Project: Alpine   Source File: KeyManager.java    License: 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 4
Source Project: spark-setup-android   Source File: Crypto.java    License: 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 5
Source Project: jdk8u-dev-jdk   Source File: BasicChecker.java    License: 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 6
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 Project: julongchain   Source File: GenerateKeyImpl.java    License: 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 8
/** {@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 9
public ProtectedStorageEntry(@NotNull ProtectedStoragePayload protectedStoragePayload,
                             @NotNull PublicKey ownerPubKey,
                             int sequenceNumber,
                             byte[] signature,
                             Clock clock) {
    this(protectedStoragePayload,
            Sig.getPublicKeyBytes(ownerPubKey),
            ownerPubKey,
            sequenceNumber,
            signature,
            clock.millis(),
            clock);
}
 
Example 10
Source Project: TencentKona-8   Source File: DSAKeyFactory.java    License: GNU General Public License v2.0 5 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 DSAPublicKeySpec) {
            DSAPublicKeySpec dsaPubKeySpec = (DSAPublicKeySpec)keySpec;
            if (SERIAL_INTEROP) {
                return new DSAPublicKey(dsaPubKeySpec.getY(),
                                    dsaPubKeySpec.getP(),
                                    dsaPubKeySpec.getQ(),
                                    dsaPubKeySpec.getG());
            } else {
                return new DSAPublicKeyImpl(dsaPubKeySpec.getY(),
                                    dsaPubKeySpec.getP(),
                                    dsaPubKeySpec.getQ(),
                                    dsaPubKeySpec.getG());
            }
        } else if (keySpec instanceof X509EncodedKeySpec) {
            if (SERIAL_INTEROP) {
                return new DSAPublicKey
                    (((X509EncodedKeySpec)keySpec).getEncoded());
            } else {
                return new DSAPublicKeyImpl
                    (((X509EncodedKeySpec)keySpec).getEncoded());
            }
        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification: " + e.getMessage());
    }
}
 
Example 11
Source Project: RipplePower   Source File: SignatureSpi.java    License: Apache License 2.0 5 votes vote down vote up
protected void engineInitVerify(PublicKey publicKey)
    throws InvalidKeyException
{
    CipherParameters param = ECUtil.generatePublicKeyParameter(publicKey);

    digest.reset();
    signer.init(false, param);
}
 
Example 12
Source Project: onos   Source File: NetconfSessionMinaImpl.java    License: 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 13
/**
 * 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 14
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 Project: che   Source File: KeycloakSigningKeyResolver.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private synchronized PublicKey getJwtPublicKey(JwsHeader<?> header) {
  String kid = header.getKeyId();
  if (header.getKeyId() == null) {
    LOG.warn(
        "'kid' is missing in the JWT token header. This is not possible to validate the token with OIDC provider keys");
    throw new JwtException("'kid' is missing in the JWT token header.");
  }
  try {
    return jwkProvider.get(kid).getPublicKey();
  } catch (JwkException e) {
    throw new JwtException(
        "Error during the retrieval of the public key during JWT token validation", e);
  }
}
 
Example 16
private static KeyStore createFireflyKeyStore() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    KeyPair fireflyKeys = keyPairGenerator.generateKeyPair();
    PrivateKey fireflySigningKey = fireflyKeys.getPrivate();
    PublicKey fireflyPublicKey = fireflyKeys.getPublic();

    KeyStore fireflyKeyStore = loadKeyStore();

    SelfSignedX509CertificateAndSigningKey issuerSelfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey.builder()
            .setDn(ROOT_DN)
            .setKeyAlgorithmName("RSA")
            .setSignatureAlgorithmName("SHA1withRSA")
            .addExtension(false, "BasicConstraints", "CA:true,pathlen:2147483647")
            .build();
    X509Certificate issuerCertificate = issuerSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();
    fireflyKeyStore.setCertificateEntry("ca", issuerCertificate);

    X509Certificate fireflyCertificate = new X509CertificateBuilder()
            .setIssuerDn(ROOT_DN)
            .setSubjectDn(FIREFLY_DN)
            .setSignatureAlgorithmName("SHA1withRSA")
            .setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey())
            .setPublicKey(fireflyPublicKey)
            .setSerialNumber(new BigInteger("1"))
            .addExtension(new BasicConstraintsExtension(false, false, -1))
            .build();
    fireflyKeyStore.setKeyEntry("firefly", fireflySigningKey, KEY_PASSWORD.toCharArray(), new X509Certificate[]{fireflyCertificate,issuerCertificate});

    return fireflyKeyStore;
}
 
Example 17
Source Project: ripple-lib-java   Source File: DSAUtil.java    License: ISC License 5 votes vote down vote up
static public AsymmetricKeyParameter generatePublicKeyParameter(
    PublicKey    key)
    throws InvalidKeyException
{
    if (key instanceof DSAPublicKey)
    {
        DSAPublicKey    k = (DSAPublicKey)key;

        return new DSAPublicKeyParameters(k.getY(),
            new DSAParameters(k.getParams().getP(), k.getParams().getQ(), k.getParams().getG()));
    }

    throw new InvalidKeyException("can't identify DSA public key: " + key.getClass().getName());
}
 
Example 18
public static void main(String[] args) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
    keyPairGenerator.initialize(1024);
    KeyPair keys = keyPairGenerator.generateKeyPair();
    PublicKey publicKey = keys.getPublic();
    byte[] sigBytes = new byte[100];

    Signature signature = Signature.getInstance("SHA1withDSA");
    signature.initVerify(publicKey);
    try {
        signature.verify(sigBytes, Integer.MAX_VALUE, 1);
    } catch (IllegalArgumentException ex) {
        // Expected
    }
}
 
Example 19
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 20
Source Project: j2objc   Source File: RevocationChecker.java    License: Apache License 2.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 21
Source Project: JDKSourceCode1.8   Source File: DSAKeyValueResolver.java    License: MIT License 5 votes vote down vote up
/**
 * Method engineResolvePublicKey
 *
 * @param element
 * @param BaseURI
 * @param storage
 * @return null if no {@link PublicKey} could be obtained
 */
public PublicKey engineLookupAndResolvePublicKey(
    Element element, String BaseURI, StorageResolver storage
) {
    if (element == null) {
        return null;
    }
    Element dsaKeyElement = null;
    boolean isKeyValue =
        XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE);
    if (isKeyValue) {
        dsaKeyElement =
            XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0);
    } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_DSAKEYVALUE)) {
        // this trick is needed to allow the RetrievalMethodResolver to eat a
        // ds:DSAKeyValue directly (without KeyValue)
        dsaKeyElement = element;
    }

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

    try {
        DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, BaseURI);
        PublicKey pk = dsaKeyValue.getPublicKey();

        return pk;
    } catch (XMLSecurityException ex) {
        if (log.isLoggable(java.util.logging.Level.FINE)) {
            log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
        }
        //do nothing
    }

    return null;
}
 
Example 22
Source Project: android-easy-checkout   Source File: Security.java    License: 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 23
/**
 * 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 24
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 25
Source Project: java_security   Source File: ElGamalTest2.java    License: 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 26
Source Project: jam-collaboration-sample   Source File: SignatureUtil.java    License: 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 27
Source Project: swim   Source File: KeyDef.java    License: 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 28
Source Project: jdk8u-jdk   Source File: Offsets.java    License: 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 29
Source Project: cas4.0.x-server-wechat   Source File: SamlUtils.java    License: 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 30
Source Project: dragonwell8_jdk   Source File: DOMKeyValue.java    License: 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;
    }
}