當前位置: 首頁>>代碼示例>>Java>>正文


Java PublicKey類代碼示例

本文整理匯總了Java中java.security.PublicKey的典型用法代碼示例。如果您正苦於以下問題:Java PublicKey類的具體用法?Java PublicKey怎麽用?Java PublicKey使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


PublicKey類屬於java.security包,在下文中一共展示了PublicKey類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: save

import java.security.PublicKey; //導入依賴的package包/類
/**
 * 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(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 (FileOutputStream fos = new FileOutputStream(publicKeyFile)) {
        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 (FileOutputStream fos = new FileOutputStream(privateKeyFile)) {
        fos.write(pkcs8EncodedKeySpec.getEncoded());
    }
}
 
開發者ID:stevespringett,項目名稱:Alpine,代碼行數:29,代碼來源:KeyManager.java

示例2: generatePublicKeyParameter

import java.security.PublicKey; //導入依賴的package包/類
static public AsymmetricKeyParameter generatePublicKeyParameter(
    PublicKey key)
    throws InvalidKeyException
{
    if (key instanceof BCMcElieceCCA2PublicKey)
    {
        BCMcElieceCCA2PublicKey k = (BCMcElieceCCA2PublicKey)key;

        return new McElieceCCA2PublicKeyParameters(k.getOIDString(), k.getN(), k.getT(), k.getG(), k.getMcElieceCCA2Parameters());
    }

    throw new InvalidKeyException("can't identify McElieceCCA2 public key: " + key.getClass().getName());
}
 
開發者ID:Appdome,項目名稱:ipack,代碼行數:14,代碼來源:McElieceCCA2KeysToParams.java

示例3: verify

import java.security.PublicKey; //導入依賴的package包/類
/**
 * 校驗數字簽名
 *
 * @param data      加密數據
 * @param publicKey 公鑰
 * @param sign      數字簽名
 * @return
 * @throws Exception
 */
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
    //解密公鑰
    byte[] keyBytes = Base64.decode(publicKey.getBytes(), Base64.DEFAULT);
    //構造X509EncodedKeySpec對象
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
    //指定加密算法
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //取公鑰匙對象
    PublicKey publicKey2 = keyFactory.generatePublic(x509EncodedKeySpec);

    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initVerify(publicKey2);
    signature.update(data);
    //驗證簽名是否正常
    return signature.verify(Base64.decode(sign, Base64.DEFAULT));

}
 
開發者ID:abook23,項目名稱:godlibrary,代碼行數:27,代碼來源:RSAUtlis.java

示例4: loadCertificate

import java.security.PublicKey; //導入依賴的package包/類
public static CertificateInfo loadCertificate(KeystoreConfiguration configuration)
    throws GeneralSecurityException, IOException {
  try {
    KeyStore keyStore = KeyStore.getInstance(configuration.getType());
    keyStore.load(getResourceAsStream(configuration.getLocation()), configuration.getPassword().toCharArray());

    Key key = keyStore.getKey(configuration.getAlias(), configuration.getKeyPassword().toCharArray());
    if (key instanceof PrivateKey) {
      X509Certificate certificate = (X509Certificate) keyStore.getCertificate(configuration.getAlias());
      PublicKey publicKey = certificate.getPublicKey();
      KeyPair keyPair = new KeyPair(publicKey, (PrivateKey) key);
      return new CertificateInfo(certificate, keyPair);
    } else {
      throw new GeneralSecurityException(configuration.getAlias() + " is not a private key!");
    }
  } catch (IOException | GeneralSecurityException e) {
    log.error("Keystore configuration: [{}] is invalid!", configuration, e);
    throw e;
  }
}
 
開發者ID:osswangxining,項目名稱:iot-edge-greengrass,代碼行數:21,代碼來源:ConfigurationTools.java

示例5: getKeyFromConfigServer

import java.security.PublicKey; //導入依賴的package包/類
private String getKeyFromConfigServer(RestTemplate keyUriRestTemplate) throws CertificateException {
    // Load available UAA servers
    discoveryClient.getServices();
    HttpEntity<Void> request = new HttpEntity<Void>(new HttpHeaders());
    String content = keyUriRestTemplate
        .exchange("http://config/api/token_key", HttpMethod.GET, request, String.class).getBody();

    if (StringUtils.isBlank(content)) {
        throw new CertificateException("Received empty certificate from config.");
    }

    InputStream fin = new ByteArrayInputStream(content.getBytes());

    CertificateFactory f = CertificateFactory.getInstance(Constants.CERTIFICATE);
    X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
    PublicKey pk = certificate.getPublicKey();
    return String.format(Constants.PUBLIC_KEY, new String(Base64.encode(pk.getEncoded())));
}
 
開發者ID:xm-online,項目名稱:xm-gate,代碼行數:19,代碼來源:MicroserviceSecurityConfiguration.java

示例6: getSuggestedSignatureAlgorithms

import java.security.PublicKey; //導入依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:Meituan-Dianping,項目名稱:walle,代碼行數:47,代碼來源:V2SchemeSigner.java

示例7: createRegisteredServicePublicKey

import java.security.PublicKey; //導入依賴的package包/類
/**
 * Create registered service public key defined.
 *
 * @param registeredService the registered service
 * @return the public key
 * @throws Exception the exception, if key cant be created
 */
private PublicKey createRegisteredServicePublicKey(final RegisteredService registeredService) throws Exception {
    if (registeredService.getPublicKey() == null) {
        logger.debug("No public key is defined for service [{}]. No encoding will take place.",
                registeredService);
        return null;
    }
    final PublicKey publicKey = registeredService.getPublicKey().createInstance();
    if (publicKey == null) {
        logger.debug("No public key instance created for service [{}]. No encoding will take place.",
                registeredService);
        return null;
    }
    return publicKey;
}
 
開發者ID:hsj-xiaokang,項目名稱:springboot-shiro-cas-mybatis,代碼行數:22,代碼來源:DefaultRegisteredServiceCipherExecutor.java

示例8: newKeyValue

import java.security.PublicKey; //導入依賴的package包/類
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);
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:13,代碼來源:DOMKeyInfoFactory.java

示例9: decodePublicKey

import java.security.PublicKey; //導入依賴的package包/類
/**
 * Create a new PublicKey from encoded X.509 data
 */
public static PublicKey decodePublicKey(byte[] encodedKey)
{
    try
    {
        EncodedKeySpec encodedkeyspec = new X509EncodedKeySpec(encodedKey);
        KeyFactory keyfactory = KeyFactory.getInstance("RSA");
        return keyfactory.generatePublic(encodedkeyspec);
    }
    catch (NoSuchAlgorithmException var3)
    {
        ;
    }
    catch (InvalidKeySpecException var4)
    {
        ;
    }

    LOGGER.error("Public key reconstitute failed!");
    return null;
}
 
開發者ID:Notoh,項目名稱:DecompiledMinecraft,代碼行數:24,代碼來源:CryptManager.java

示例10: encodeKey

import java.security.PublicKey; //導入依賴的package包/類
private void encodeKey(
    Key                 key,
    DataOutputStream    dOut)
    throws IOException
{
    byte[]      enc = key.getEncoded();

    if (key instanceof PrivateKey)
    {
        dOut.write(KEY_PRIVATE);
    }
    else if (key instanceof PublicKey)
    {
        dOut.write(KEY_PUBLIC);
    }
    else
    {
        dOut.write(KEY_SECRET);
    }

    dOut.writeUTF(key.getFormat());
    dOut.writeUTF(key.getAlgorithm());
    dOut.writeInt(enc.length);
    dOut.write(enc);
}
 
開發者ID:Appdome,項目名稱:ipack,代碼行數:26,代碼來源:BcKeyStoreSpi.java

示例11: updateState

import java.security.PublicKey; //導入依賴的package包/類
private void updateState(X509Certificate cert)
    throws CertPathValidatorException
{
    issuerInfo = new OCSPResponse.IssuerInfo(anchor, cert);

    // Make new public key if parameters are missing
    PublicKey pubKey = cert.getPublicKey();
    if (PKIX.isDSAPublicKeyWithoutParams(pubKey)) {
        // pubKey needs to inherit DSA parameters from prev key
        pubKey = BasicChecker.makeInheritedParamsKey(pubKey, prevPubKey);
    }
    prevPubKey = pubKey;
    crlSignFlag = certCanSignCrl(cert);
    if (certIndex > 0) {
        certIndex--;
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:18,代碼來源:RevocationChecker.java

示例12: getPublicKeyFromInternalResolvers

import java.security.PublicKey; //導入依賴的package包/類
/**
 * Searches the per-KeyInfo KeyResolvers for public keys
 *
 * @return The public key contained in this Node.
 * @throws KeyResolverException
 */
PublicKey getPublicKeyFromInternalResolvers() throws KeyResolverException {
    for (KeyResolverSpi keyResolver : internalKeyResolvers) {
        if (log.isLoggable(java.util.logging.Level.FINE)) {
            log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
        }
        keyResolver.setSecureValidation(secureValidation);
        Node currentChild = this.constructionElement.getFirstChild();
        String uri = this.getBaseURI();
        while (currentChild != null)      {
            if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
                for (StorageResolver storage : storageResolvers) {
                    PublicKey pk =
                        keyResolver.engineLookupAndResolvePublicKey(
                            (Element) currentChild, uri, storage
                        );

                    if (pk != null) {
                        return pk;
                    }
                }
            }
            currentChild = currentChild.getNextSibling();
        }
    }

    return null;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:34,代碼來源:KeyInfo.java

示例13: getPublicKey

import java.security.PublicKey; //導入依賴的package包/類
public PublicKey getPublicKey(SubjectPublicKeyInfo publicKeyInfo)
    throws PEMException
{
    try
    {
        String algorithm =  publicKeyInfo.getAlgorithm().getAlgorithm().getId();

        if (X9ObjectIdentifiers.id_ecPublicKey.getId().equals(algorithm))
        {
            algorithm = "ECDSA";
        }

        KeyFactory keyFactory = helper.createKeyFactory(algorithm);

        return keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyInfo.getEncoded()));
    }
    catch (Exception e)
    {
        throw new PEMException("unable to convert key pair: " + e.getMessage(), e);
    }
}
 
開發者ID:Appdome,項目名稱:ipack,代碼行數:22,代碼來源:JcaPEMKeyConverter.java

示例14: RespID

import java.security.PublicKey; //導入依賴的package包/類
public RespID(
    PublicKey   key)
    throws OCSPException
{
    try
    {
        // TODO Allow specification of a particular provider
        MessageDigest digest = OCSPUtil.createDigestInstance("SHA1", null);

        ASN1InputStream aIn = new ASN1InputStream(key.getEncoded());
        SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject());

        digest.update(info.getPublicKeyData().getBytes());

        ASN1OctetString keyHash = new DEROctetString(digest.digest());

        this.id = new ResponderID(keyHash);
    }
    catch (Exception e)
    {
        throw new OCSPException("problem creating ID: " + e, e);
    }
}
 
開發者ID:Appdome,項目名稱:ipack,代碼行數:24,代碼來源:RespID.java

示例15: encryptByPublic

import java.security.PublicKey; //導入依賴的package包/類
/**
 * 用公鑰對字符串進行加密
 *
 * @param data 原文
 */
private static byte[] encryptByPublic(byte[] data, byte[] publicKey) {
    byte[] result = null;
    // 得到公鑰
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
    try {
        KeyFactory kf = KeyFactory.getInstance(RSA);

        PublicKey keyPublic = kf.generatePublic(keySpec);
        // 加密數據
        Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
        cp.init(Cipher.ENCRYPT_MODE, keyPublic);
        cp.doFinal(data);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("RSA加密", "公鑰加密失敗");
    }
    return result;
}
 
開發者ID:JJS-CN,項目名稱:JBase,代碼行數:24,代碼來源:RsaUtils.java


注:本文中的java.security.PublicKey類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。