类java.security.PublicKey源码实例Demo

下面列出了怎么用java.security.PublicKey的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: jdk8u-jdk   文件: DHKeyFactory.java
/**
 * 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);
    }
}
 
源代码2 项目: Alpine   文件: KeyManager.java
/**
 * 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());
    }
}
 
源代码3 项目: spark-setup-android   文件: Crypto.java
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);
    }
}
 
源代码4 项目: jdk8u-dev-jdk   文件: BasicChecker.java
/**
 * 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);
    }
}
 
源代码5 项目: freehealth-connector   文件: STSServiceImpl.java
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;
}
 
源代码6 项目: MaxKey   文件: CertCrypto.java
/**
 * <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;
}
 
源代码7 项目: julongchain   文件: GenerateKeyImpl.java
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);
}
 
/** {@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;
}
 
源代码9 项目: bisq   文件: ProtectedStorageEntry.java
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);
}
 
源代码10 项目: TencentKona-8   文件: DSAKeyFactory.java
/**
 * 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());
    }
}
 
源代码11 项目: RipplePower   文件: SignatureSpi.java
protected void engineInitVerify(PublicKey publicKey)
    throws InvalidKeyException
{
    CipherParameters param = ECUtil.generatePublicKeyParameter(publicKey);

    digest.reset();
    signer.init(false, param);
}
 
源代码12 项目: onos   文件: NetconfSessionMinaImpl.java
private PublicKey getPublicKey(byte[] keyBytes, String type)
        throws NoSuchAlgorithmException, InvalidKeySpecException {

    X509EncodedKeySpec spec =
            new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance(type);
    return kf.generatePublic(spec);
}
 
源代码13 项目: flashback   文件: CertificateKeyStoreFactory.java
/**
 * 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;
}
 
源代码14 项目: openjdk-jdk8u   文件: DOMKeyInfoFactory.java
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);
    }
}
 
源代码15 项目: che   文件: KeycloakSigningKeyResolver.java
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);
  }
}
 
源代码16 项目: wildfly-core   文件: KeyStoresTestCase.java
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;
}
 
源代码17 项目: ripple-lib-java   文件: DSAUtil.java
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());
}
 
源代码18 项目: jdk8u-jdk   文件: VerifyRangeCheckOverflow.java
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
    }
}
 
源代码19 项目: openjdk-jdk8u-backup   文件: RevocationChecker.java
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());
}
 
源代码20 项目: j2objc   文件: RevocationChecker.java
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());
}
 
源代码21 项目: JDKSourceCode1.8   文件: DSAKeyValueResolver.java
/**
 * 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;
}
 
源代码22 项目: android-easy-checkout   文件: Security.java
/**
 * 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));
}
 
/**
 * 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;
}
 
源代码24 项目: TencentKona-8   文件: X509CertSelectorTest.java
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);
}
 
源代码25 项目: java_security   文件: ElGamalTest2.java
/**
 * 初始化密钥对
 * @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;
	
}
 
源代码26 项目: jam-collaboration-sample   文件: SignatureUtil.java
/**
 * 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);
    } 
}
 
源代码27 项目: swim   文件: KeyDef.java
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());
}
 
源代码28 项目: jdk8u-jdk   文件: Offsets.java
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);
}
 
源代码29 项目: cas4.0.x-server-wechat   文件: SamlUtils.java
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");
}
 
源代码30 项目: dragonwell8_jdk   文件: DOMKeyValue.java
public PublicKey getPublicKey() throws KeyException {
    if (publicKey == null) {
        throw new KeyException("can't convert KeyValue to PublicKey");
    } else {
        return publicKey;
    }
}
 
 类所在包
 同包方法