本文整理匯總了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;
}
示例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;
}
示例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);
}
示例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));
}
示例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);
}
示例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);
}
}
示例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;
}
示例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));
}
示例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);
}
示例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;
}
示例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);
}
}
示例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);
}
}
}
示例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);
}
}
示例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));
}
示例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));
}