当前位置: 首页>>代码示例>>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;未经允许,请勿转载。