java.security.spec.X509EncodedKeySpec Java Examples

The following examples show how to use java.security.spec.X509EncodedKeySpec. 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 File: IosRSAKeyFactory.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Override
 protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
     throws InvalidKeySpecException {
  //The KeySpec for Private Key is PKCS8
if (keySpec instanceof PKCS8EncodedKeySpec ) {
  return new IosRSAKey.IosRSAPrivateKey(((PKCS8EncodedKeySpec) keySpec).getEncoded());  
}
   if (keySpec instanceof X509EncodedKeySpec) {
     X509EncodedKeySpec x509Spec = (X509EncodedKeySpec) keySpec;
     return new IosRSAKey.IosRSAPrivateKey(x509Spec.getEncoded());
   } else if (keySpec instanceof RSAPrivateKeySpec) {
     return new IosRSAKey.IosRSAPrivateKey((RSAPrivateKeySpec) keySpec);
   }
   throw new InvalidKeySpecException(
       "Must use PKCS8EncodedKeySpec, X509EncodedKeySpec or RSAPrivateKeySpec; was "
           + keySpec.getClass().getName());
 }
 
Example #2
Source File: SecretUtil.java    From DataLink with Apache License 2.0 6 votes vote down vote up
/**
 * 加密<br>
 * 用公钥加密 encryptByPublicKey
 *
 * @param data 裸的原始数据
 * @param key  经过base64加密的公钥
 * @return 结果也采用base64加密
 * @throws Exception
 */
public static String encryptRSA(String data, String key) {
    try {
        // 对公钥解密,公钥被base64加密过
        byte[] keyBytes = decryptBASE64(key);

        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);

        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        return encryptBASE64(cipher.doFinal(data.getBytes(ENCODING)));
    } catch (Exception e) {
        throw DataXException.asDataXException(
                FrameworkErrorCode.SECRET_ERROR, "rsa加密出错", e);
    }
}
 
Example #3
Source File: ElexisEnvironmentLoginDialog.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
public ElexisEnvironmentLoginDialog(Shell shell, String openidClientSecret, String keycloakUrl,
	String realmPublicKey){
	super(shell);
	
	logger = LoggerFactory.getLogger(getClass());
	
	oauthService = new ServiceBuilder(ElexisEnvironmentLoginContributor.OAUTH2_CLIENT_ID)
		.apiSecret(openidClientSecret).defaultScope("openid").callback(CALLBACK_URL)
		.build(KeycloakApi.instance(keycloakUrl, ElexisEnvironmentLoginContributor.REALM_ID));
	
	KeyFactory kf;
	try {
		kf = KeyFactory.getInstance("RSA");
		X509EncodedKeySpec keySpecX509 =
			new X509EncodedKeySpec(Base64.getDecoder().decode(realmPublicKey));
		RSAPublicKey publicKey = (RSAPublicKey) kf.generatePublic(keySpecX509);
		
		jwtParser = Jwts.parserBuilder().setSigningKey(publicKey).build();
	} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
		logger.error("Initialization error", e);
	}
	
}
 
Example #4
Source File: ExportControlled.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public static RSAPublicKey decodeRSAPublicKey(String key) throws RSAException {

        if (key == null) {
            throw ExceptionFactory.createException(RSAException.class, "Key parameter is null");
        }

        int offset = key.indexOf("\n") + 1;
        int len = key.indexOf("-----END PUBLIC KEY-----") - offset;

        // TODO: use standard decoders with Java 6+
        byte[] certificateData = Base64Decoder.decode(key.getBytes(), offset, len);

        X509EncodedKeySpec spec = new X509EncodedKeySpec(certificateData);
        try {
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return (RSAPublicKey) kf.generatePublic(spec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw ExceptionFactory.createException(RSAException.class, "Unable to decode public key", e);
        }
    }
 
Example #5
Source File: CryptoUtil.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private static PublicKey loadPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {

        String publicKeyPEM = FileUtils.readFileToString(new File(TransactionConstants.PUBLIC_KEY),
                                                         StandardCharsets.UTF_8);
        // strip of header, footer, newlines, whitespaces.
        publicKeyPEM = publicKeyPEM
                .replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\\s", "");

        // decode to get the binary DER representation.
        byte[] publicKeyDER = Base64.getDecoder().decode(publicKeyPEM);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyDER));
    }
 
Example #6
Source File: BaseEncryptionManager.java    From samples-android with Apache License 2.0 6 votes vote down vote up
private void initEncodeCipher(String keyAlias, int mode) throws GeneralSecurityException {
    PublicKey key = mKeyStore.getCertificate(keyAlias).getPublicKey();

    // workaround for using public key
    // from https://developer.android.com/reference/android/security/keystore/KeyGenParameterSpec.html#known-issues
    PublicKey unrestricted = KeyFactory.getInstance(key.getAlgorithm())
            .generatePublic(new X509EncodedKeySpec(key.getEncoded()));

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // from https://code.google.com/p/android/issues/detail?id=197719
        OAEPParameterSpec spec = new OAEPParameterSpec("SHA-256", "MGF1",
                MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);

        mCipher.init(mode, unrestricted, spec);
    } else {
        mCipher.init(mode, unrestricted);
    }
}
 
Example #7
Source File: MyOtrKeyManager.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a local key pair. Be careful. If there is already an key pair,
 * it will override it
 * 
 * @param sessionID
 *            the sessionID that is identified with the local machine
 */
public void generateLocalKeyPair(SessionID sessionID) {
    if (sessionID == null)
        return;

    String accountID = sessionID.getAccountID();
    KeyPair keyPair;
    try {
        keyPair = KeyPairGenerator.getInstance("DSA").genKeyPair();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return;
    }

    // Store Public Key.
    PublicKey pubKey = keyPair.getPublic();
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKey.getEncoded());

    this.store.setProperty(accountID + ".publicKey", x509EncodedKeySpec.getEncoded());

    // Store Private Key.
    PrivateKey privKey = keyPair.getPrivate();
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privKey.getEncoded());

    this.store.setProperty(accountID + ".privateKey", pkcs8EncodedKeySpec.getEncoded());
}
 
Example #8
Source File: DHKeyFactory.java    From openjdk-8-source with 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 #9
Source File: PFSecurityUtils.java    From PFLockScreen-Android with Apache License 2.0 6 votes vote down vote up
private void initEncodeCipher(Cipher cipher, String alias, KeyStore keyStore)
        throws PFSecurityException {
    try {
        final PublicKey key = keyStore.getCertificate(alias).getPublicKey();
        final PublicKey unrestricted = KeyFactory.getInstance(key.getAlgorithm()).generatePublic(
                new X509EncodedKeySpec(key.getEncoded()));
        final OAEPParameterSpec spec = new OAEPParameterSpec("SHA-256", "MGF1",
                MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);
        cipher.init(Cipher.ENCRYPT_MODE, unrestricted, spec);
    } catch (KeyStoreException | InvalidKeySpecException |
            NoSuchAlgorithmException | InvalidKeyException |
            InvalidAlgorithmParameterException e) {
        throw new PFSecurityException(
                "Can not initialize Encode Cipher:" + e.getMessage(),
                PFSecurityUtilsErrorCodes.ERROR_INIT_ENDECODE_CIPHER
        );
    }
}
 
Example #10
Source File: Util.java    From XPrivacy with GNU General Public License v3.0 6 votes vote down vote up
private static PublicKey getPublicKey(Context context) throws Throwable {
	// Read public key
	String sPublicKey = "";
	InputStreamReader isr = new InputStreamReader(context.getAssets().open("XPrivacy_public_key.txt"), "UTF-8");
	BufferedReader br = new BufferedReader(isr);
	String line = br.readLine();
	while (line != null) {
		if (!line.startsWith("-----"))
			sPublicKey += line;
		line = br.readLine();
	}
	br.close();
	isr.close();

	// Create public key
	byte[] bPublicKey = Base64.decode(sPublicKey, Base64.NO_WRAP);
	KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	X509EncodedKeySpec encodedPubKeySpec = new X509EncodedKeySpec(bPublicKey);
	return keyFactory.generatePublic(encodedPubKeySpec);
}
 
Example #11
Source File: DHKeyFactory.java    From jdk8u-jdk with 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 #12
Source File: RsaUtil.java    From uexam-mysql with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String rsaEncode(String publicCertificate, String text) {
    try {
        byte[] publicBytes = baseStrToByte(publicCertificate);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PublicKey pubKey = keyFactory.generatePublic(keySpec);
        // get an RSA cipher object and print the provider
        final Cipher cipher = Cipher.getInstance(ALGORITHM);
        // encrypt the plain text using the public key
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] cipherBytes = cipher.doFinal(text.getBytes(CHAR_SET));
        return baseByteToStr(cipherBytes);
    } catch (Exception e) {
        logger.error("publicCertificate:{}  \r\n  text:{}", publicCertificate, text, e);
    }
    return null;
}
 
Example #13
Source File: Crypto.java    From paystack-android with Apache License 2.0 6 votes vote down vote up
private static PublicKey getPublicKeyFromString(String pubKey) throws AuthenticationException {

    PublicKey key;

    try {
      //init keyfactory
      KeyFactory kf = KeyFactory.getInstance(ALGORITHM);

      //decode the key into a byte array
      byte[] keyBytes = Base64.decode(pubKey, Base64.NO_WRAP);

      //create spec
      X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);

      //generate public key
      key = kf.generatePublic(spec);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
        throw new AuthenticationException("Invalid public key: " + e.getMessage());
    }
    return key;


  }
 
Example #14
Source File: RsaSsaPss.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This specific doesn't verify in combination with its document, so
 * I wanted to look at its contents. As RSASSA-PSS does not allow to
 * read the original hash from the decrypted signature bytes, this
 * did not help at all.
 */
@Test
public void testDecryptSLMBC_PSS_Test1() throws IOException, CMSException, GeneralSecurityException
{
    Cipher cipherNoPadding = Cipher.getInstance("RSA/ECB/NoPadding");
    KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA");

    try (   InputStream resource = getClass().getResourceAsStream("SLMBC-PSS-Test1.cms")    )
    {
        CMSSignedData cmsSignedData = new CMSSignedData(resource);
        for (SignerInformation signerInformation : (Iterable<SignerInformation>)cmsSignedData.getSignerInfos().getSigners())
        {
            Collection<X509CertificateHolder> x509CertificateHolders = cmsSignedData.getCertificates().getMatches(signerInformation.getSID());
            if (x509CertificateHolders.size() != 1)
            {
                Assert.fail("Cannot uniquely determine signer certificate.");
            }
            X509CertificateHolder x509CertificateHolder = x509CertificateHolders.iterator().next();
            PublicKey publicKey = rsaKeyFactory.generatePublic(new X509EncodedKeySpec(x509CertificateHolder.getSubjectPublicKeyInfo().getEncoded()));
            cipherNoPadding.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] bytes = cipherNoPadding.doFinal(signerInformation.getSignature());

            Files.write(new File(RESULT_FOLDER, "SLMBC-PSS-Test1-signature-decoded").toPath(), bytes);
        }
    }
}
 
Example #15
Source File: PKCS10CertificationRequest.java    From TorrentEngine with GNU General Public License v3.0 6 votes vote down vote up
public PublicKey getPublicKey(
    String  provider)
    throws NoSuchAlgorithmException, NoSuchProviderException,
            InvalidKeyException
{
    SubjectPublicKeyInfo    subjectPKInfo = reqInfo.getSubjectPublicKeyInfo();

    try
    {
        X509EncodedKeySpec      xspec = new X509EncodedKeySpec(new DERBitString(subjectPKInfo).getBytes());
        AlgorithmIdentifier     keyAlg = subjectPKInfo.getAlgorithmId ();

        return KeyFactory.getInstance(keyAlg.getObjectId().getId (), provider).generatePublic(xspec);
    }
    catch (InvalidKeySpecException e)
    {
        throw new InvalidKeyException("error encoding public key");
    }
}
 
Example #16
Source File: DSAKeyFactory.java    From Bytecoder with Apache License 2.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 DSAPublicKeySpec) {
            DSAPublicKeySpec dsaPubKeySpec = (DSAPublicKeySpec)keySpec;
            return new DSAPublicKeyImpl(dsaPubKeySpec.getY(),
                                dsaPubKeySpec.getP(),
                                dsaPubKeySpec.getQ(),
                                dsaPubKeySpec.getG());
        } else if (keySpec instanceof X509EncodedKeySpec) {
            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 #17
Source File: JDKKeyFactory.java    From TorrentEngine with GNU General Public License v3.0 6 votes vote down vote up
protected PublicKey engineGeneratePublic(
    KeySpec    keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof X509EncodedKeySpec)
    {
        try
        {
            return JDKKeyFactory.createPublicKeyFromDERStream(
                        new ByteArrayInputStream(((X509EncodedKeySpec)keySpec).getEncoded()));
        }
        catch (Exception e)
        {
            throw new InvalidKeySpecException(e.toString());
        }
    }
    else if (keySpec instanceof ECPublicKeySpec)
    {
        return new JCEECPublicKey(algorithm, (ECPublicKeySpec)keySpec);
    }
	
    throw new InvalidKeySpecException("Unknown KeySpec type.");
}
 
Example #18
Source File: GeneratedEcdsaKeyProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected KeyWrapper loadKey(RealmModel realm, ComponentModel model) {
       String privateEcdsaKeyBase64Encoded = model.getConfig().getFirst(GeneratedEcdsaKeyProviderFactory.ECDSA_PRIVATE_KEY_KEY);
       String publicEcdsaKeyBase64Encoded = model.getConfig().getFirst(GeneratedEcdsaKeyProviderFactory.ECDSA_PUBLIC_KEY_KEY);
       String ecInNistRep = model.getConfig().getFirst(GeneratedEcdsaKeyProviderFactory.ECDSA_ELLIPTIC_CURVE_KEY);

       try {
           PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decode(privateEcdsaKeyBase64Encoded));
           KeyFactory kf = KeyFactory.getInstance("EC");
           PrivateKey decodedPrivateKey = kf.generatePrivate(privateKeySpec);

           X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.decode(publicEcdsaKeyBase64Encoded));
           PublicKey decodedPublicKey = kf.generatePublic(publicKeySpec);

           KeyPair keyPair = new KeyPair(decodedPublicKey, decodedPrivateKey);

           return createKeyWrapper(keyPair, ecInNistRep);
       } catch (Exception e) {
           logger.warnf("Exception at decodeEcdsaPublicKey. %s", e.toString());
           return null;
       }

   }
 
Example #19
Source File: DHKeyFactory.java    From openjdk-jdk9 with 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 #20
Source File: TokenService.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Get the public key details (value and issuer) for CSP API
 */
private void populatePublicKeyDetails() {
    final PublicKeyResponse response = restTemplate.getForObject(config.getCspAuthUrl(), PublicKeyResponse.class);
    publicKeyIssuer = response.getIssuer();
    final String rawPublicKey = response.getValue();
    String pem = rawPublicKey.replaceAll("-----BEGIN (.*)-----", "")
            .replaceAll("-----END (.*)----", "")
            .replaceAll("\n", "");
    try {
        publicKey = KeyFactory.getInstance(KEYS_ALGORITHM)
                .generatePublic(new X509EncodedKeySpec(Base64.getDecoder()
                        .decode(pem)));
    } catch (Exception e) {
        LOGGER.error("Failed to generate public key");
    }
}
 
Example #21
Source File: ECDSASignature.java    From fabric-net-server with Apache License 2.0 6 votes vote down vote up
/**
 * ECDSA公钥签名校验
 *
 * @param info         待签名字符串
 * @param sign         签名值
 * @param publicKeyStr 公钥字符串内容
 * @param encode       编码
 * @return 校验结果
 */
public boolean verifyByStr(String info, String sign, String publicKeyStr, @Nullable String encode) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("EC");
        PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decodeBase64(publicKeyStr)));
        Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
        signature.initVerify(publicKey);
        if (encode == null) {
            signature.update(info.getBytes());
        } else {
            signature.update(info.getBytes(encode));
        }
        return signature.verify(Base64.decodeBase64(sign));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | SignatureException | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example #22
Source File: RSAEncryptCoder.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] encrypt(byte[] publicKey, byte[] byteContent) {
	X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
	KeyFactory kf;
	PublicKey keyPublic;
	try {
		kf = KeyFactory.getInstance(RSA_KEY);
		keyPublic = kf.generatePublic(keySpec);
	} catch (Exception e) {
		throw new BaseException("generate public key error: " + e.getMessage() , e);
	}

	byte[] result = chunkedCipher(keyPublic, Cipher.ENCRYPT_MODE, encryptSize, byteContent);
	return result;
}
 
Example #23
Source File: DSAKeyFactory.java    From openjdk-jdk8u with 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 #24
Source File: CryptManager.java    From FishingBot with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a new PublicKey from encoded X.509 data
 */
public static PublicKey decodePublicKey(byte[] par0ArrayOfByte) {
    try {
        X509EncodedKeySpec var1 = new X509EncodedKeySpec(par0ArrayOfByte);
        KeyFactory var2 = KeyFactory.getInstance("RSA");
        return var2.generatePublic(var1);
    } catch (NoSuchAlgorithmException var3) {
        var3.printStackTrace();
    } catch (InvalidKeySpecException var4) {
        var4.printStackTrace();
    }

    System.err.println("Public key reconstitute failed!");
    return null;
}
 
Example #25
Source File: ConstantPasswords.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void bad8a() throws Exception {
    new DESKeySpec(null); // should not be reported
    byte[] key = {1, 2, 3, 4, 5, 6, 7, 8};
    DESKeySpec spec = new DESKeySpec(key);
    KeySpec spec2 = new DESedeKeySpec(key);
    KerberosKey kerberosKey = new KerberosKey(null, key, 0, 0);
    System.out.println(spec.getKey()[0] + kerberosKey.getKeyType());
    new SecretKeySpec(key, "alg");
    new SecretKeySpec(key, 0, 0, "alg");
    new X509EncodedKeySpec(key);
    new PKCS8EncodedKeySpec(key);
    new KeyRep(null, "alg", "format", key);
    new KerberosTicket(null, null, null, key, 0, null, null, null, null, null, null);
    new DSAPublicKeyImpl(key);
}
 
Example #26
Source File: DSAKeyFactory.java    From jdk8u60 with 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 #27
Source File: TestECDSA.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void test(Provider provider, String pub, String priv, byte[] sig) throws Exception {

        KeyFactory kf = KeyFactory.getInstance("EC", provider);
        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(parse(pub));
        PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(parse(priv));

        PrivateKey privateKey = kf.generatePrivate(privSpec);
        PublicKey publicKey = kf.generatePublic(pubSpec);

        if (false) {
            sign(provider, "SHA1withECDSA", privateKey, data1Raw);
//          sign(provider, "NONEwithECDSA", privateKey, data1SHA);
            return;
        }

        // verify known-good and known-bad signatures using SHA1withECDSA and NONEwithECDSA
        verify(provider, "SHA1withECDSA", publicKey, data1Raw, sig, true);
        verify(provider, "SHA1withECDSA", publicKey, data2Raw, sig, false);

        verify(provider, "NONEwithECDSA", publicKey, data1SHA, sig, true);
        verify(provider, "NONEwithECDSA", publicKey, data2SHA, sig, false);

        System.out.println("Testing with default signature format: ASN.1");
        testSigning(provider, privateKey, publicKey, false);

        System.out.println("Testing with IEEE P1363 signature format");
        testSigning(provider, privateKey, publicKey, true);
    }
 
Example #28
Source File: CryptoServiceImpl.java    From paymentgateway with GNU General Public License v3.0 5 votes vote down vote up
private PublicKey initializePublicKey(String data) {
	try {
		data = StringUtils.remove(data, "-----BEGIN PUBLIC KEY-----");
		data = StringUtils.remove(data, "-----END PUBLIC KEY-----");
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(data));
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		return keyFactory.generatePublic(keySpec);
	}
	catch (Exception e) {
		throw new IllegalArgumentException("Invalid public key: ", e);
	}
}
 
Example #29
Source File: RSAUtil.java    From ApplicationPower with Apache License 2.0 5 votes vote down vote up
/**
 * 得到公钥
 *
 * @param publicKey 密钥字符串(经过base64编码)
 * @return RSAPublicKey
 */
public static RSAPublicKey getPublicKey(String publicKey) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #30
Source File: X509CertSelectorTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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);
}