当前位置: 首页>>代码示例>>Java>>正文


Java RSAPublicKeySpec类代码示例

本文整理汇总了Java中java.security.spec.RSAPublicKeySpec的典型用法代码示例。如果您正苦于以下问题:Java RSAPublicKeySpec类的具体用法?Java RSAPublicKeySpec怎么用?Java RSAPublicKeySpec使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


RSAPublicKeySpec类属于java.security.spec包,在下文中一共展示了RSAPublicKeySpec类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: createPublicKey

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
/**
 * 从hex string生成公钥
 * 
 * @param stringN
 * @param stringE
 * @return 构造好的公钥
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PublicKey createPublicKey(String stringN, String stringE)
		throws NoSuchAlgorithmException, InvalidKeySpecException {
	try {
		BigInteger N = new BigInteger(stringN, 16); // hex base
		BigInteger E = new BigInteger(stringE, 16); // hex base

		RSAPublicKeySpec spec = new RSAPublicKeySpec(N, E);
		KeyFactory kf = KeyFactory.getInstance("RSA");
		return kf.generatePublic(spec);
	} catch (Exception e) {
		e.printStackTrace();
	}

	return null;
}
 
开发者ID:mugua2015,项目名称:VerifySignedJar,代码行数:25,代码来源:VerfiyPKCS7Info.java

示例2: encrypt

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
public static String encrypt(byte[] keyBytes, String plainText)
		throws Exception {
	PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
	KeyFactory factory = KeyFactory.getInstance("RSA");
	PrivateKey privateKey = factory.generatePrivate(spec);
	Cipher cipher = Cipher.getInstance("RSA");
       try {
	    cipher.init(Cipher.ENCRYPT_MODE, privateKey);
       } catch (InvalidKeyException e) {
           //For IBM JDK, 原因请看解密方法中的说明
           RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
           RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
           Key fakePublicKey = KeyFactory.getInstance("RSA").generatePublic(publicKeySpec);
           cipher = Cipher.getInstance("RSA");
           cipher.init(Cipher.ENCRYPT_MODE, fakePublicKey);
       }

	byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
	String encryptedString = Base64.byteArrayToBase64(encryptedBytes);

	return encryptedString;
}
 
开发者ID:huang-up,项目名称:mycat-src-1.6.1-RELEASE,代码行数:23,代码来源:DecryptUtil.java

示例3: loadRsaKeys

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
private KeyPair loadRsaKeys(Path publicFile, Path privateFile)
	throws GeneralSecurityException, ReflectiveOperationException,
	IOException
{
	KeyFactory factory = KeyFactory.getInstance("RSA");
	
	// load public key
	PublicKey publicKey;
	try(ObjectInputStream in =
		new ObjectInputStream(Files.newInputStream(publicFile)))
	{
		publicKey = factory.generatePublic(new RSAPublicKeySpec(
			(BigInteger)in.readObject(), (BigInteger)in.readObject()));
	}
	
	// load private key
	PrivateKey privateKey;
	try(ObjectInputStream in =
		new ObjectInputStream(Files.newInputStream(privateFile)))
	{
		privateKey = factory.generatePrivate(new RSAPrivateKeySpec(
			(BigInteger)in.readObject(), (BigInteger)in.readObject()));
	}
	
	return new KeyPair(publicKey, privateKey);
}
 
开发者ID:Wurst-Imperium,项目名称:Wurst-MC-1.12,代码行数:27,代码来源:Encryption.java

示例4: getPublicKey

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
/**
 * Get the public key that is used to verify the JWT from the user service. We assume the key is
 * an RSA key.
 *
 * @throws NoSuchAlgorithmException
 */
private PublicKey getPublicKey()
    throws Base64Exception, InvalidKeySpecException, NoSuchAlgorithmException {
  String url =
      "https://" + libertyHostname + ":" + libertySslPort + "/jwt/ibm/api/jwtUserBuilder/jwk";
  Response response = processRequest(url, "GET", null, null);
  assertEquals(
      "HTTP response code should have been " + Status.OK.getStatusCode() + ".",
      Status.OK.getStatusCode(),
      response.getStatus());

  // Liberty returns the keys in an array.  We'll grab the first one (there
  // should only be one).
  JsonObject jwkResponse = toJsonObj(response.readEntity(String.class));
  JsonArray jwkArray = jwkResponse.getJsonArray("keys");
  JsonObject jwk = jwkArray.getJsonObject(0);
  BigInteger modulus = new BigInteger(1, Base64Utility.decode(jwk.getString("n"), true));
  BigInteger publicExponent = new BigInteger(1, Base64Utility.decode(jwk.getString("e"), true));
  return KeyFactory.getInstance("RSA")
      .generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
}
 
开发者ID:OpenLiberty,项目名称:sample-acmegifts,代码行数:27,代码来源:JWTVerifier.java

示例5: unmarshalKeyValue

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
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);
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:22,代码来源:DOMKeyValue.java

示例6: loadPublicKeyFromKeyStore

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
/**
 * 从KeyStore获取公钥
 * @param location
 * @param alias
 * @param storeType
 * @param storePass
 * @param keyPass
 * @return
 */
public static PublicKey loadPublicKeyFromKeyStore(String location, String alias, String storeType, String storePass, String keyPass) {
    try {
        storeType = null == storeType ? KeyStore.getDefaultType() : storeType;
        keyPass = keyPass == null ? storePass : keyPass;
        KeyStore keyStore = KeyStore.getInstance(storeType);
        InputStream is = new FileInputStream(location);
        keyStore.load(is, storePass.toCharArray());

        RSAPrivateCrtKey key = (RSAPrivateCrtKey) keyStore.getKey(alias, keyPass.toCharArray());
        RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(),
                key.getPublicExponent());
        PublicKey publicKey = KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(spec);
        return publicKey;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:warlock-china,项目名称:azeroth,代码行数:27,代码来源:RSA.java

示例7: encrypt

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
public static String encrypt(byte[] keyBytes, String plainText)
        throws Exception {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory factory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = factory.generatePrivate(spec);
    Cipher cipher = Cipher.getInstance("RSA");
    try {
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
    } catch (InvalidKeyException e) {
        //For IBM JDK
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
        RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
        Key fakePublicKey = KeyFactory.getInstance("RSA").generatePublic(publicKeySpec);
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, fakePublicKey);
    }

    byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
    String encryptedString = Base64.byteArrayToBase64(encryptedBytes);

    return encryptedString;
}
 
开发者ID:actiontech,项目名称:dble,代码行数:23,代码来源:DecryptUtil.java

示例8: main

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
public static void main(String[] args) throws GeneralSecurityException, UnsupportedEncodingException {

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

        KeyFactory fact = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),
                RSAPublicKeySpec.class);
        RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),
                RSAPrivateKeySpec.class);

        publicKey = fact.generatePublic(pub);
        privateKey = fact.generatePrivate(priv);

        String foo = rsaEncrypt("foo");

        byte[] decode = Base64.getDecoder().decode("foo");
        System.out.println(Base64.getEncoder().encodeToString(decode));

        System.out.println(rsaDecrypt(foo));

    }
 
开发者ID:daishicheng,项目名称:outcomes,代码行数:24,代码来源:Main.java

示例9: unmarshalKeyValue

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
@Override
RSAPublicKey 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",
                                                        XMLSignature.XMLNS);
    BigInteger modulus = decode(modulusElem);
    Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem,
                                                          "Exponent",
                                                          XMLSignature.XMLNS);
    BigInteger exponent = decode(exponentElem);
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
    return (RSAPublicKey) generatePublicKey(rsakf, spec);
}
 
开发者ID:Legostaev,项目名称:xmlsec-gost,代码行数:24,代码来源:DOMKeyValue.java

示例10: readKey

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
private static RSAPublicKey readKey(final String key) throws Exception {
    final byte[] encKey = Base64.decodeBase64(key.split(" ")[1]);
    final DataInputStream dis = new DataInputStream(new ByteArrayInputStream(encKey));

    final byte[] header = readElement(dis);
    final String pubKeyFormat = new String(header);
    if (!pubKeyFormat.equals("ssh-rsa")) {
        throw new RuntimeException("Unsupported format");
    }

    final byte[] publicExponent = readElement(dis);
    final byte[] modulus = readElement(dis);

    final KeySpec spec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));
    final KeyFactory keyFactory = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
    final RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(spec);

    return pubKey;
}
 
开发者ID:MissionCriticalCloud,项目名称:cosmic,代码行数:20,代码来源:RSAHelper.java

示例11: loadPublicKeyFromKeyStore

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
/**
   * 从KeyStore获取公钥
   * @param location
   * @param alias
   * @param storeType
   * @param storePass
   * @param keyPass
   * @return
   */
  public static PublicKey loadPublicKeyFromKeyStore(String location,String alias,String storeType,String storePass,String keyPass){
      try {			
      	storeType = null == storeType ? KeyStore.getDefaultType() : storeType;
      	keyPass = keyPass == null ? storePass : keyPass;
      	KeyStore keyStore = KeyStore.getInstance(storeType);
      	InputStream is = new FileInputStream(location);
      	keyStore.load(is, storePass.toCharArray());
      	
      	RSAPrivateCrtKey key = (RSAPrivateCrtKey) keyStore.getKey(alias, keyPass.toCharArray());
	RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(),
			key.getPublicExponent());
	PublicKey publicKey = KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(spec);
          return publicKey;
} catch (Exception e) {
	throw new RuntimeException(e);
}
  }
 
开发者ID:vakinge,项目名称:jeesuite-libs,代码行数:27,代码来源:RSA.java

示例12: testLegacySignatures

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
/**
 * Tests legacy signatures. In this context we use the term legacy signatures for signatures that
 * are not conforming to the PKCS #1 standard, but are sometimes generated by buggy signers. So
 * far this test considers both accepting and rejecting such signatures as valid behavior.
 *
 * <p>Currently we check for just one type of legacy signatures: i.e., a missing NULL parameter in
 * the ASN encoding of the hash. BouncyCastle and the SunJCE accept this signature, Conscrypt does
 * not.
 *
 * <p>Some references that support accepting this signature:
 * https://codereview.chromium.org/1690123002/
 * https://groups.google.com/a/chromium.org/forum/#!topic/chromium-reviews/Jo5S7HtEABI claims that
 * 7% of the responses in the Online Certificate Status Protocol (OCSP) miss the NULL parameter
 */
@Test
public void testLegacySignatures() throws Exception {
  RSAPublicKeySpec key = RSA_KEY1;
  String algorithm = ALGORITHM_KEY1;
  byte[] message = "Test".getBytes("UTF-8");
  Signature verifier = Signature.getInstance(algorithm);
  KeyFactory kf = KeyFactory.getInstance("RSA");
  PublicKey pub = kf.generatePublic(key);
  for (String signature : LEGACY_SIGNATURES_KEY1) {
    byte[] signatureBytes = TestUtil.hexToBytes(signature);
    verifier.initVerify(pub);
    verifier.update(message);
    boolean verified = false;
    try {
      verified = verifier.verify(signatureBytes);
    } catch (SignatureException ex) {
      verified = false;
    }
    if (verified) {
      System.out.println("Verfied legacy signature:" + signature);
    } else {
      System.out.println("Rejected legacy signature:" + signature);
    }
  }
}
 
开发者ID:google,项目名称:wycheproof,代码行数:40,代码来源:RsaSignatureTest.java

示例13: getPublicKey

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
public PublicKey getPublicKey() {
	try {
		SubjectPublicKeyInfo subjectPublicKeyInfo = getCertificate().getSubjectPublicKeyInfo();
		RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(subjectPublicKeyInfo);

		RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());

		KeyFactory kf = KeyFactory.getInstance(DEFAULT_KEY_ALG);
		PublicKey rsaPub = kf.generatePublic(rsaSpec);

		return rsaPub;

	} catch (Exception e) {
		throw new RuntimeException("Error while getting Public Key: " + e.getMessage(), e);
	}
}
 
开发者ID:fabiusks,项目名称:cert-services,代码行数:17,代码来源:IdentityContainer.java

示例14: sshPublicKey

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
static PublicKey sshPublicKey(String key){
    String[] split = key.split(" ");
    dieIf(split.length != 3, () -> "Unexpected file format");
    dieIf(!split[0].equals("ssh-rsa"), () -> "Unrecognised file header");

    byte[] keyBytes = Base64.getDecoder().decode(split[1]);
    DataInputStream in = new DataInputStream(new ByteArrayInputStream(keyBytes));

    byte[] header = new byte[rethrow(in::readInt)];
    rethrow(() -> in.readFully(header));

    dieIf(! new String(header).equals("ssh-rsa"), () -> "Unrecognised header");

    byte[] exponent = new byte[rethrow(in::readInt)];
    rethrow(() -> in.readFully(exponent));
    BigInteger e = new BigInteger(exponent);

    byte[] modulo = new byte[rethrow(in::readInt)];
    rethrow(() -> in.readFully(modulo));
    BigInteger m = new BigInteger(modulo);

    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(m, e);
    return rethrow(() -> KeyFactory.getInstance("RSA").generatePublic(rsaPublicKeySpec));
}
 
开发者ID:tsmarsh,项目名称:UnderBar,代码行数:25,代码来源:RSA.java

示例15: getRsaPublicKeyWithSingleRsaJwkInputReturnsListWithSingleRsaPublicKeyObject

import java.security.spec.RSAPublicKeySpec; //导入依赖的package包/类
@Test
public void getRsaPublicKeyWithSingleRsaJwkInputReturnsListWithSingleRsaPublicKeyObject() throws NoSuchAlgorithmException, InvalidKeySpecException,
        ParseException {
    Object jwk = new JSONParser()
            .parse("{\"kty\": \"RSA\", \"use\": \"sig\", \"n\": \"AK9LhraAG8Tz55FnLk99Q1V-rJEAS7PhXcaXK5z4tw0IOWVXVHKf7xXibbPRwQVIyF4YUaoanmrkzUa0aU-oWXGdBsBmo4CIhj8jcY5YZFtZF7ynov_3a-8-dQNcfjc6_1U6bBw95bsP6C-oJhaXmX2fnAuVpcK0BjkQ3zoI7SGikTLGwclPJ1WsvTo2pX3HR6QCc1puvDjaO3gBA0mn_S6q3TL6mOqYDIeD3b6aklNbobHe1QSm1rRLO7I-j7B-qiAGb_gGLTRndBc4ZI-sWkwQGOkZeEugJukgspmWAmFYd821RXQ9M8egqCYsVM7FsEm_raKvSG2ehxFo7ZSVbLM\", \"e\": \"AQAB\"}");

    BigInteger modulus = new BigInteger(
            "22128946737323913239210052479333027707901510060102775675830991813349418659538199300647898430584144500806059458278321518777044762899512296866600872394644380219013320495156971514431190023600729602211122577883306928327035481763181383360484196857466673122026840292263234856687762092039930273840883706411057986999291723263528956058054902470342623926525220419403492184749748080083440782860930153041629788053392850350190345701856884676367792841834106393147716901597512639433053628947682648446566660847625123370647049602729290059736582541200917525808306486312868092094709254446973240693245640735124383753810943940731642145971");
    BigInteger publicExponent = new BigInteger("65537");
    PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent));

    List<PublicKey> publicKeyList = Converter.getRsaPublicKeysByJwk(jwk);

    assertNotNull(publicKeyList);
    assertEquals(1, publicKeyList.size());
    assertEquals(publicKey, publicKeyList.get(0));
}
 
开发者ID:RUB-NDS,项目名称:JOSEPH,代码行数:18,代码来源:ConverterTest.java


注:本文中的java.security.spec.RSAPublicKeySpec类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。