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


Java KeyPair.getPrivate方法代碼示例

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


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

示例1: readWalletFile

import java.security.KeyPair; //導入方法依賴的package包/類
private PrivateKey readWalletFile(final char[] userPassword) throws FileNotFoundException,
        IOException, ClassNotFoundException, InvalidKeySpecException,
        InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException {
    
    final WalletInformation walletInformation;
    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
        walletInformation = (WalletInformation) ois.readObject();
    } catch(IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Error with file {0}", ex.getMessage());
        return null;
    }
    
    final KeyPair keyPair = Cryptography.keyPairFromWalletInformation(userPassword, walletInformation);
    if (keyPair == null) {
        System.out.println("The password you entered is incorrect");
        return null;
    }
    this.publicKey = keyPair.getPublic();
    return keyPair.getPrivate();
}
 
開發者ID:StanIsAdmin,項目名稱:CrashCoin,代碼行數:21,代碼來源:Wallet.java

示例2: GameServerThread

import java.security.KeyPair; //導入方法依賴的package包/類
public GameServerThread(Socket con)
{
	_connection = con;
	_connectionIp = con.getInetAddress().getHostAddress();
	try
	{
		_in = _connection.getInputStream();
		_out = new BufferedOutputStream(_connection.getOutputStream());
	}
	catch (IOException e)
	{
		e.printStackTrace();
	}
	KeyPair pair = GameServerTable.getInstance().getKeyPair();
	_privateKey = (RSAPrivateKey) pair.getPrivate();
	_publicKey = (RSAPublicKey) pair.getPublic();
	_blowfish = new NewCrypt("_;v.]05-31!|+-%xT!^[$\00");
	start();
}
 
開發者ID:L2jBrasil,項目名稱:L2jBrasil,代碼行數:20,代碼來源:GameServerThread.java

示例3: initKey

import java.security.KeyPair; //導入方法依賴的package包/類
/**
 * 初始化密鑰
 * 
 * @return Map 密鑰對兒 Map
 * @throws Exception
 */
public static Map<String, Object> initKey() throws Exception {
	// 實例化密鑰對兒生成器
	KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
	// 初始化密鑰對兒生成器
	keyPairGen.initialize(KEY_SIZE);
	// 生成密鑰對兒
	KeyPair keyPair = keyPairGen.generateKeyPair();
	// 公鑰
	RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
	// 私鑰
	RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
	// 封裝密鑰
	Map<String, Object> keyMap = new HashMap<String, Object>(2);
	keyMap.put(PUBLIC_KEY, publicKey);
	keyMap.put(PRIVATE_KEY, privateKey);
	return keyMap;
}
 
開發者ID:youngMen1,項目名稱:JAVA-,代碼行數:24,代碼來源:RSACoder.java

示例4: GameServerThread

import java.security.KeyPair; //導入方法依賴的package包/類
public GameServerThread(Socket con)
{
	_connection = con;
	_connectionIp = con.getInetAddress().getHostAddress();
	try
	{
		_in = _connection.getInputStream();
		_out = new BufferedOutputStream(_connection.getOutputStream());
	}
	catch (IOException e)
	{
		_log.warning(getClass().getSimpleName() + ": " + e.getMessage());
	}
	final KeyPair pair = GameServerTable.getInstance().getKeyPair();
	_privateKey = (RSAPrivateKey) pair.getPrivate();
	_publicKey = (RSAPublicKey) pair.getPublic();
	_blowfish = new NewCrypt("_;v.]05-31!|+-%xT!^[$\00");
	setName(getClass().getSimpleName() + "-" + getId() + "@" + _connectionIp);
	start();
}
 
開發者ID:rubenswagner,項目名稱:L2J-Global,代碼行數:21,代碼來源:GameServerThread.java

示例5: testKeyPairGeneration

import java.security.KeyPair; //導入方法依賴的package包/類
@Test(groups = TEST_GROUP_UTILS, description = "Used to generate initial key testing pair")
public void testKeyPairGeneration() throws Exception {
    KeyPair keyPair = TokenUtils.generateKeyPair(2048);
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    // extract the encoded private key, this is an unencrypted PKCS#8 private key
    byte[] privateKeyEnc = privateKey.getEncoded();
    byte[] privateKeyPem = Base64.getEncoder().encode(privateKeyEnc);
    String privateKeyPemStr = new String(privateKeyPem);
    System.out.println("-----BEGIN RSA PRIVATE KEY-----");
    int column = 0;
    for(int n = 0; n < privateKeyPemStr.length(); n ++) {
        System.out.print(privateKeyPemStr.charAt(n));
        column ++;
        if(column == 64) {
            System.out.println();
            column = 0;
        }
    }
    System.out.println("\n-----END RSA PRIVATE KEY-----");

    byte[] publicKeyEnc = publicKey.getEncoded();
    byte[] publicKeyPem = Base64.getEncoder().encode(publicKeyEnc);
    String publicKeyPemStr = new String(publicKeyPem);
    System.out.println("-----BEGIN RSA PUBLIC KEY-----");
    column = 0;
    for(int n = 0; n < publicKeyPemStr.length(); n ++) {
        System.out.print(publicKeyPemStr.charAt(n));
        column ++;
        if(column == 64) {
            System.out.println();
            column = 0;
        }
    }
    System.out.println("\n-----END RSA PUBLIC KEY-----");
}
 
開發者ID:eclipse,項目名稱:microprofile-jwt-auth,代碼行數:37,代碼來源:TokenUtilsTest.java

示例6: initKey

import java.security.KeyPair; //導入方法依賴的package包/類
/**
 * 初始化密鑰
 *
 * @return
 * @throws Exception
 */
public static Map<String, Object> initKey() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator
            .getInstance(Algorithm.RSA.getType());
    keyPairGen.initialize(1024);

    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();    // 公鑰
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();     // 私鑰
    Map<String, Object> keyMap = new HashMap<String, Object>(2);

    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, privateKey);
    return keyMap;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:21,代碼來源:Codec.java

示例7: AsymmetricKeys

import java.security.KeyPair; //導入方法依賴的package包/類
public AsymmetricKeys() throws Exception {
    super(asymmetricKeyAlgorithm);
    KeyPairGenerator keygen = KeyPairGenerator.getInstance(asymmetricKeyAlgorithm);
    keygen.initialize(keySize);
    KeyPair pair = keygen.generateKeyPair();
    publicKey = pair.getPublic();
    privateKey = pair.getPrivate();
}
 
開發者ID:Baizey,項目名稱:Helpers,代碼行數:9,代碼來源:AsymmetricKeys.java

示例8: main

import java.security.KeyPair; //導入方法依賴的package包/類
public static void main(String[] args) {

        try {

            KeyStore keyStore = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
            keyStore.load(null, null);

            // Generate a certificate to use for testing
            CertAndKeyGen gen = new CertAndKeyGen("RSA", "SHA256withRSA");
            gen.generate(2048);
            Certificate cert =
                gen.getSelfCertificate(new X500Name("CN=test"), 3600);
            String alias = "JDK-8172244";
            char[] password = "password".toCharArray();
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");

            // generate a private key for the certificate
            kpg.initialize(2048);
            KeyPair keyPair = kpg.generateKeyPair();
            PrivateKey privKey = keyPair.getPrivate();
            // need to bypass checks to store the private key without the cert
            Field spiField = KeyStore.class.getDeclaredField("keyStoreSpi");
            spiField.setAccessible(true);
            KeyStoreSpi spi = (KeyStoreSpi) spiField.get(keyStore);
            spi.engineSetKeyEntry(alias, privKey, password, new Certificate[0]);
            keyStore.store(null, null);

            keyStore.getCertificateAlias(cert);
            keyStore.deleteEntry(alias);
            // test passes if no exception is thrown
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:35,代碼來源:KeyStoreEmptyCertChain.java

示例9: genKeyPair

import java.security.KeyPair; //導入方法依賴的package包/類
/**
 * <p>
 * 生成密鑰對(公鑰和私鑰)
 * </p>
 *
 * @return
 * @throws Exception
 */
public static Map<String, Object> genKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyPairGen.initialize(1024);
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    Map<String, Object> keyMap = new HashMap<String, Object>(2);
    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, privateKey);
    return keyMap;
}
 
開發者ID:angcyo,項目名稱:RLibrary,代碼行數:20,代碼來源:RSAUtils.java

示例10: sizeTest

import java.security.KeyPair; //導入方法依賴的package包/類
/**
 * @param kpair test key pair.
 * @return true if test passed. false if test failed.
 */
private static boolean sizeTest(KeyPair kpair) {
    RSAPrivateKey priv = (RSAPrivateKey) kpair.getPrivate();
    RSAPublicKey pub = (RSAPublicKey) kpair.getPublic();

    // test the getModulus method
    if ((priv instanceof RSAKey) && (pub instanceof RSAKey)) {
        if (!priv.getModulus().equals(pub.getModulus())) {
            System.err.println("priv.getModulus() = " + priv.getModulus());
            System.err.println("pub.getModulus() = " + pub.getModulus());
            return false;
        }
    }
    return true;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:KeySizeTest.java

示例11: generateSelfSignedCertChain

import java.security.KeyPair; //導入方法依賴的package包/類
private Certificate generateSelfSignedCertChain(KeyPair kp, X500Name subject, String hostname)
        throws CertificateException, OperatorCreationException, IOException {
    SecureRandom rand = new SecureRandom();
    PrivateKey privKey = kp.getPrivate();
    PublicKey pubKey = kp.getPublic();
    ContentSigner sigGen = new JcaContentSignerBuilder(DEFAULT_SIG_ALG).build(privKey);

    SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(
            ASN1Sequence.getInstance(pubKey.getEncoded()));

    Date now = new Date(); // now

    /* force it to use a English/Gregorian dates for the cert, hardly anyone
       ever looks at the cert metadata anyway, and its very likely that they
       understand English/Gregorian dates */
    Calendar c = new GregorianCalendar(Locale.ENGLISH);
    c.setTime(now);
    c.add(Calendar.YEAR, 1);
    Time startTime = new Time(now, Locale.ENGLISH);
    Time endTime = new Time(c.getTime(), Locale.ENGLISH);

    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(
            subject,
            BigInteger.valueOf(rand.nextLong()),
            startTime,
            endTime,
            subject,
            subPubKeyInfo);

    if (hostname != null) {
        GeneralNames subjectAltName = new GeneralNames(
                new GeneralName(GeneralName.iPAddress, hostname));
        v3CertGen.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
    }

    X509CertificateHolder certHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}
 
開發者ID:uhuru-mobile,項目名稱:mobile-store,代碼行數:39,代碼來源:LocalRepoKeyStore.java

示例12: testInteropSignWolfVerify

import java.security.KeyPair; //導入方法依賴的package包/類
@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);
        }
    }
}
 
開發者ID:wolfSSL,項目名稱:wolfcrypt-jni,代碼行數:56,代碼來源:WolfCryptSignatureTest.java

示例13: generateKeyPair

import java.security.KeyPair; //導入方法依賴的package包/類
@Override
public KeyPair generateKeyPair() {
    KeyPair dsigKeyPair = dsigGenerator.generateKeyPair();
    KeyPair accKeyPair = accGenerator.generateKeyPair();
    PublicKey publicKey = new GSRSSPublicKey(algorithm, dsigKeyPair.getPublic(), accKeyPair.getPublic());
    PrivateKey privateKey = new GSRSSPrivateKey(algorithm, dsigKeyPair.getPrivate(), accKeyPair.getPrivate());
    return new KeyPair(publicKey, privateKey);
}
 
開發者ID:woefe,項目名稱:xmlrss,代碼行數:9,代碼來源:GSRSSKeyPairGenerator.java

示例14: setKeyPair

import java.security.KeyPair; //導入方法依賴的package包/類
public void setKeyPair(final KeyPair keyPair) {
    CommonHelper.assertNotNull("keyPair", keyPair);
    this.privateKey = (RSAPrivateKey) keyPair.getPrivate();
    this.publicKey = (RSAPublicKey) keyPair.getPublic();
}
 
開發者ID:yaochi,項目名稱:pac4j-plus,代碼行數:6,代碼來源:RSAEncryptionConfiguration.java

示例15: XMLDSigWithSecMgr

import java.security.KeyPair; //導入方法依賴的package包/類
XMLDSigWithSecMgr() throws Exception {
    setup();
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS
        ("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS("http://www.w3.org/2000/xmlns/",
        "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = kpg.genKeyPair();

    // the policy only grants this test SocketPermission to accept, resolve
    // and connect to localhost so that it can dereference 2nd reference
    URI policyURI =
        new File(System.getProperty("test.src", "."), "policy").toURI();
    Policy.setPolicy
        (Policy.getInstance("JavaPolicy", new URIParameter(policyURI)));
    System.setSecurityManager(new SecurityManager());

    try {
        // generate a signature with SecurityManager enabled
        ArrayList refs = new ArrayList();
        refs.add(fac.newReference
            ("", sha1,
             Collections.singletonList
                (fac.newTransform(Transform.ENVELOPED,
                 (TransformParameterSpec) null)), null, null));
        refs.add(fac.newReference("http://localhost:" + ss.getLocalPort()
            + "/anything.txt", sha1));
        SignedInfo si = fac.newSignedInfo(withoutComments,
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
        XMLSignature sig = fac.newXMLSignature(si, null);
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), envelope);
        sig.sign(dsc);

        // validate a signature with SecurityManager enabled
        DOMValidateContext dvc = new DOMValidateContext
            (kp.getPublic(), envelope.getFirstChild());

        // disable secure validation mode so that http reference will work
        dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

        sig = fac.unmarshalXMLSignature(dvc);
        if (!sig.validate(dvc)) {
            throw new Exception
                ("XMLDSigWithSecMgr signature validation FAILED");
        }
    } catch (SecurityException se) {
        throw new Exception("XMLDSigWithSecMgr FAILED", se);
    }
    ss.close();
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:54,代碼來源:XMLDSigWithSecMgr.java


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