Java 类java.security.PublicKey 实例源码

项目: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(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());
    }
}
项目:ipack    文件:McElieceCCA2KeysToParams.java   
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());
}
项目:godlibrary    文件:RSAUtlis.java   
/**
 * 校验数字签名
 *
 * @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));

}
项目:iot-edge-greengrass    文件:ConfigurationTools.java   
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;
  }
}
项目:xm-gate    文件:MicroserviceSecurityConfiguration.java   
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())));
}
项目:walle    文件:V2SchemeSigner.java   
/**
 * 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);
    }
}
项目:springboot-shiro-cas-mybatis    文件:DefaultRegisteredServiceCipherExecutor.java   
/**
 * 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;
}
项目:jdk8u-jdk    文件: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);
    }
}
项目:DecompiledMinecraft    文件:CryptManager.java   
/**
 * 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;
}
项目:ipack    文件:BcKeyStoreSpi.java   
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);
}
项目:openjdk-jdk10    文件:RevocationChecker.java   
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--;
    }
}
项目:openjdk-jdk10    文件:KeyInfo.java   
/**
 * 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;
}
项目:ipack    文件:JcaPEMKeyConverter.java   
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);
    }
}
项目:ipack    文件:RespID.java   
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);
    }
}
项目:JBase    文件:RsaUtils.java   
/**
 * 用公钥对字符串进行加密
 *
 * @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;
}
项目:OpenJSharp    文件:X509IssuerSerialResolver.java   
/** @inheritDoc */
public PublicKey engineLookupAndResolvePublicKey(
    Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {

    X509Certificate cert =
        this.engineLookupResolveX509Certificate(element, baseURI, storage);

    if (cert != null) {
        return cert.getPublicKey();
    }

    return null;
}
项目:nutz-pay    文件:SecureUtil.java   
public static boolean validateSignBySoft(PublicKey publicKey,
                                         byte[] signData, byte[] srcData) throws Exception {
    Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA1RSA, "BC");
    st.initVerify(publicKey);
    st.update(srcData);
    return st.verify(signData);
}
项目:ipack    文件:JcaContentVerifierProviderBuilder.java   
private SignatureOutputStream createSignatureStream(AlgorithmIdentifier algorithm, PublicKey publicKey)
    throws OperatorCreationException
{
    try
    {
        Signature sig = helper.createSignature(algorithm);

        sig.initVerify(publicKey);

        return new SignatureOutputStream(sig);
    }
    catch (GeneralSecurityException e)
    {
        throw new OperatorCreationException("exception on setup: " + e, e);
    }
}
项目:AndroidBasicLibs    文件:RSA.java   
/**
 * 校验数字签名
 *
 * @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); // 解密由base64编码的公钥
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  // 构造X509EncodedKeySpec对象
    KeyFactory keyFactory = KeyFactory.getInstance(CipherType.RSA.getType());  // KEY_ALGORITHM 指定的加密算法
    PublicKey pubKey = keyFactory.generatePublic(keySpec);   // 取公钥对象

    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initVerify(pubKey);
    signature.update(data);

    return signature.verify(BASE64.decode(sign));
}
项目:jdk8u-jdk    文件:DOMKeyValue.java   
PublicKey unmarshalKeyValue(Element kvtElem)
    throws MarshalException
{
    if (rsakf == null) {
        try {
            rsakf = KeyFactory.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException
                ("unable to create RSA KeyFactory: " + e.getMessage());
        }
    }
    Element modulusElem = DOMUtils.getFirstChildElement(kvtElem,
                                                        "Modulus");
    modulus = new DOMCryptoBinary(modulusElem.getFirstChild());
    Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem,
                                                          "Exponent");
    exponent = new DOMCryptoBinary(exponentElem.getFirstChild());
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus.getBigNum(),
                                                 exponent.getBigNum());
    return generatePublicKey(rsakf, spec);
}
项目:xitk    文件:ProxyP11Slot.java   
private P11Identity parseGenerateKeypairResult(byte[] resp) throws P11TokenException {
    if (resp == null) {
        throw new P11TokenException("server returned no result");
    }
    Asn1P11EntityIdentifier ei;
    try {
        ei = Asn1P11EntityIdentifier.getInstance(resp);
    } catch (BadAsn1ObjectException ex) {
        throw new P11TokenException(
                "invalid ASN1 object Asn1P11EntityIdentifier: " + ex.getMessage(), ex);
    }
    if (!slotId.equals(ei.slotId().slotId())) {
        throw new P11TokenException("");
    }
    P11EntityIdentifier entityId = ei.entityId();

    PublicKey publicKey = getPublicKey(entityId.objectId());
    return new ProxyP11Identity(this, entityId, publicKey, null);
}
项目:lams    文件:SigningUtil.java   
/**
 * Verify the signature value computed over the supplied input against the supplied signature value.
 * 
 * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of verification key
 * supplied.
 * 
 * @param verificationKey the key with which to compute and verify the signature
 * @param jcaAlgorithmID the Java JCA algorithm ID to use
 * @param signature the computed signature value received from the signer
 * @param input the input over which the signature is computed and verified
 * @return true if the signature value computed over the input using the supplied key and algorithm ID is identical
 *         to the supplied signature value
 * @throws SecurityException thrown if the signature computation or verification process results in an error
 */
public static boolean verify(PublicKey verificationKey, String jcaAlgorithmID, byte[] signature, byte[] input)
        throws SecurityException {
    Logger log = getLogger();

    log.debug("Verifying signature over input using public key of type {} and JCA algorithm ID {}", verificationKey
            .getAlgorithm(), jcaAlgorithmID);

    try {
        Signature sig = Signature.getInstance(jcaAlgorithmID);
        sig.initVerify(verificationKey);
        sig.update(input);
        return sig.verify(signature);
    } catch (GeneralSecurityException e) {
        log.error("Error during signature verification", e);
        throw new SecurityException("Error during signature verification", e);
    }
}
项目:jdk8u-jdk    文件:X509CertSelector.java   
/**
 * Sets the subjectPublicKey criterion. The
 * {@code X509Certificate} must contain the specified subject public
 * key. If {@code null}, no subjectPublicKey check will be done.
 *
 * @param key the subject public key to check for (or {@code null})
 * @see #getSubjectPublicKey
 */
public void setSubjectPublicKey(PublicKey key) {
    if (key == null) {
        subjectPublicKey = null;
        subjectPublicKeyBytes = null;
    } else {
        subjectPublicKey = key;
        subjectPublicKeyBytes = key.getEncoded();
    }
}
项目:azeroth    文件:RSA.java   
/**
 * 还原公钥,X509EncodedKeySpec 用于构建公钥的规范
 *
 * @param keyBytes
 * @return
 */
public static PublicKey loadPublicKey(byte[] keyBytes) {
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);

    try {
        KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
        return publicKey;
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}
项目:ipack    文件:KeyFactorySpi.java   
protected PublicKey engineGeneratePublic(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof ECPublicKeySpec)
    {
        return new BCECPublicKey(algorithm, (ECPublicKeySpec)keySpec, configuration);
    }
    else if (keySpec instanceof java.security.spec.ECPublicKeySpec)
    {
        return new BCECPublicKey(algorithm, (java.security.spec.ECPublicKeySpec)keySpec, configuration);
    }

    return super.engineGeneratePublic(keySpec);
}
项目:mDL-ILP    文件:ECCUtils.java   
/**
 * Implement the ECKA algorithm (EG variant) in order to calculate the ShS (shared secret) from the provided
 * static and ephemeral keys from the same curve.
 * @param privateKey the private key to use for the ShS calculation.
 * @param publicKey the public key to use for the ShS calculation.
 * @return the calculated shared secret.
 */
public static byte[] calculateECKAShS(PrivateKey privateKey, PublicKey publicKey) {

    try {
        ECKABasicAgreement basicAgreement = new ECKABasicAgreement();
        basicAgreement.init(ECUtil.generatePrivateKeyParameter(privateKey));

        return basicAgreement.calculatePoint(ECUtil.generatePublicKeyParameter(publicKey)).getEncoded();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    return null;
}
项目:openjdk-jdk10    文件: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);
}
项目:ipack    文件:X509CertificateObject.java   
public final void verify(
    PublicKey   key,
    String      sigProvider)
    throws CertificateException, NoSuchAlgorithmException,
    InvalidKeyException, NoSuchProviderException, SignatureException
{
    String    sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm());
    Signature signature = Signature.getInstance(sigName, sigProvider);

    checkSignature(key, signature);
}
项目:openjdk-jdk10    文件:X509IssuerSerialResolver.java   
/** @inheritDoc */
public PublicKey engineLookupAndResolvePublicKey(
    Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {

    X509Certificate cert =
        this.engineLookupResolveX509Certificate(element, baseURI, storage);

    if (cert != null) {
        return cert.getPublicKey();
    }

    return null;
}
项目:wolfcrypt-jni    文件:WolfCryptSignatureTest.java   
@Test
public void testInteropSignWolfVerify()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           SignatureException, InvalidKeyException,
           InvalidAlgorithmParameterException {

    String toSign = "Hello World";
    byte[] toSignBuf = toSign.getBytes();
    byte[] signature;

    for (int i = 0; i < wolfJCEAlgos.length; i++) {

        Signature signer =
            Signature.getInstance(wolfJCEAlgos[i]);
        Signature verifier =
            Signature.getInstance(wolfJCEAlgos[i], "wolfJCE");

        assertNotNull(signer);
        assertNotNull(verifier);

        Provider prov = signer.getProvider();
        if (prov.equals("wolfJCE")) {
            /* bail out, there isn't another implementation to interop
             * against by default */
            return;
        }

        SecureRandom rand =
            SecureRandom.getInstance("HashDRBG", "wolfJCE");
        assertNotNull(rand);

        /* generate key pair */
        KeyPair pair = generateKeyPair(wolfJCEAlgos[i], rand);
        assertNotNull(pair);

        PrivateKey priv = pair.getPrivate();
        PublicKey  pub  = pair.getPublic();

        /* generate signature */
        signer.initSign(priv);
        signer.update(toSignBuf, 0, toSignBuf.length);
        signature = signer.sign();

        /* verify signature */
        verifier.initVerify(pub);
        verifier.update(toSignBuf, 0, toSignBuf.length);
        boolean verified = verifier.verify(signature);

        if (verified != true) {
            fail("Signature verification failed when generating with " +
                    "system default JCE provider and verifying with " +
                    "wolfJCE provider, iteration " + i);
        }
    }
}
项目:lams    文件:RSA_SHA1.java   
private PublicKey getPublicKeyFromDerCert(byte[] certObject)
        throws GeneralSecurityException {
    CertificateFactory fac = CertificateFactory.getInstance("X509");
    ByteArrayInputStream in = new ByteArrayInputStream(certObject);
    X509Certificate cert = (X509Certificate)fac.generateCertificate(in);
    return cert.getPublicKey();
}
项目:xlight_android_native    文件:Crypto.java   
static PublicKey buildPublicKey(byte[] rawBytes) throws CryptoException {
    X509EncodedKeySpec spec = new X509EncodedKeySpec(rawBytes);
    KeyFactory kf = getRSAKeyFactory();
    try {
        return kf.generatePublic(spec);
    } catch (InvalidKeySpecException e) {
        throw new CryptoException(e);
    }
}
项目:lams    文件:SecurityHelper.java   
/**
 * Get a simple, minimal credential containing a public key, and optionally a private key.
 * 
 * @param publicKey the public key to wrap
 * @param privateKey the private key to wrap, which may be null
 * @return a credential containing the key(s) specified
 */
public static BasicCredential getSimpleCredential(PublicKey publicKey, PrivateKey privateKey) {
    if (publicKey == null) {
        throw new IllegalArgumentException("A public key is required");
    }
    BasicCredential cred = new BasicCredential();
    cred.setPublicKey(publicKey);
    cred.setPrivateKey(privateKey);
    return cred;
}
项目:TPlayer    文件:Crypto.java   
private PublicKey readKeyFromStream(InputStream keyStream) throws IOException {
    ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(keyStream));
    try {
        PublicKey pubKey = (PublicKey) oin.readObject();
        return pubKey;
    } catch (Exception e) {
        Log.e("readKeyFromStream", e);
        return null;
    } finally {
        oin.close();
    }
}
项目:HerbertyyRepository    文件:RSA.java   
/**
* RSA验签名检查
* @param content 待签名数据
* @param sign 签名值
* @param alipay_public_key 支付宝公钥
* @param input_charset 编码格式
* @return 布尔值
*/
public static boolean verify(String content, String sign, String alipay_public_key, String input_charset)
{
    try 
    {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encodedKey = Base64.decode(alipay_public_key);
        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));


        java.security.Signature signature = java.security.Signature
        .getInstance(SIGN_ALGORITHMS);

        signature.initVerify(pubKey);
        signature.update( content.getBytes(input_charset) );

        boolean bverify = signature.verify( Base64.decode(sign) );
        return bverify;

    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }

    return false;
}
项目:springboot-shiro-cas-mybatis    文件:AbstractSamlObjectBuilder.java   
/**
 * Sign SAML response.
 *
 * @param samlResponse the SAML response
 * @param privateKey the private key
 * @param publicKey the public key
 * @return the response
 */
public final String signSamlResponse(final String samlResponse,
                                     final PrivateKey privateKey, final PublicKey publicKey) {
    final Document doc = constructDocumentFromXml(samlResponse);

    if (doc != null) {
        final org.jdom.Element signedElement = signSamlElement(doc.getRootElement(),
                privateKey, publicKey);
        doc.setRootElement((org.jdom.Element) signedElement.detach());
        return new XMLOutputter().outputString(doc);
    }
    throw new RuntimeException("Error signing SAML Response: Null document");
}
项目:jdk8u-jdk    文件:CertificateX509Key.java   
/**
 * Set the attribute value.
 */
public void set(String name, Object obj) throws IOException {
    if (name.equalsIgnoreCase(KEY)) {
        this.key = (PublicKey)obj;
    } else {
        throw new IOException("Attribute name not recognized by " +
                              "CertAttrSet: CertificateX509Key.");
    }
}
项目:HerbertyyRepository    文件:RSAUtils.java   
/**
 * 使用N、e值还原公钥
 *
 * @param modulus
 * @param publicExponent
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PublicKey getPublicKey(String modulus, String publicExponent)
        throws NoSuchAlgorithmException, InvalidKeySpecException
{
    BigInteger bigIntModulus = new BigInteger(modulus);
    BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
    RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
    KeyFactory keyFactory = KeyFactory.getInstance(RSA);
    PublicKey publicKey = keyFactory.generatePublic(keySpec);
    return publicKey;
}
项目:crypto-shuffle    文件:JsonUtil.java   
static PublicKey bytesToPublicKey(@NotNull byte[] keyBytes) {
    try {
        @NotNull X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(keyBytes);
        @NotNull KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(X509publicKey);
    } catch (Exception e) {
        throw new RuntimeException("Problem converting string to PublicKey: " + bytesToBase64String(keyBytes), e);
    }
}
项目:ipack    文件:SignatureSpi.java   
protected void engineInitVerify(PublicKey publicKey)
    throws InvalidKeyException
{
    CipherParameters param = ECUtil.generatePublicKeyParameter(publicKey);

    digest.reset();
    signer.init(false, param);
}