Java 类java.security.spec.RSAPublicKeySpec 实例源码
项目:VerifySignedJar
文件:VerfiyPKCS7Info.java
/**
* 从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;
}
项目:mycat-src-1.6.1-RELEASE
文件:DecryptUtil.java
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;
}
项目:Wurst-MC-1.12
文件:Encryption.java
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);
}
项目:sample-acmegifts
文件:JWTVerifier.java
/**
* 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));
}
项目:OpenJSharp
文件: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);
}
项目:azeroth
文件:RSA.java
/**
* 从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);
}
}
项目: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);
}
项目:openjdk-jdk10
文件: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);
}
项目:dble
文件:DecryptUtil.java
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;
}
项目:outcomes
文件:Main.java
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));
}
项目:openjdk9
文件: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);
}
项目:xmlsec-gost
文件:DOMKeyValue.java
@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);
}
项目:cosmic
文件:RSAHelper.java
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;
}
项目:jeesuite-libs
文件:RSA.java
/**
* 从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);
}
}
项目:wycheproof
文件:RsaSignatureTest.java
/**
* 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);
}
}
}
项目: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);
}
项目:lookaside_java-1.8.0-openjdk
文件: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);
}
项目:cert-services
文件:IdentityContainer.java
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);
}
}
项目:UnderBar
文件:RSA.java
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));
}
项目:JOSEPH
文件:ConverterTest.java
@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));
}
项目:JOSEPH
文件:ConverterTest.java
@Test
public void getRsaPublicKeyWithTwoKeysRsaAndEcJwkInputReturnsListWithSingleRsaPublicKeyObject() throws NoSuchAlgorithmException, InvalidKeySpecException,
ParseException {
Object jwk = new JSONParser()
.parse("{\"keys\":[{\"kty\":\"EC\", \"crv\":\"P-256\", \"x\":\"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4\", \"y\":\"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM\", \"use\":\"enc\", \"kid\":\"1\"},{\"kty\":\"RSA\", \"n\": \"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2 QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqb w0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw\", \"e\":\"AQAB\", \"alg\":\"RS256\", \"kid\":\"2011-04-29\"}]}");
BigInteger modulus = new BigInteger(
"-5682458471133998388349435224633069349339468533284902336027705964449388702650944577143355769222747143645802928997396746788844516020279137866835783191591333722847996520065852710220990368127004199808401899736680560956431068787853232744544770599290862357208116339307372204787434279492353211428856678472586090071739438019744959023980640454937307928948909285462577350157199294652794553602056459172956409144930859767392952162694193223130644537748426311422152249961861449835863678305650703998634078098161038037616498189346650489296709705191330089861202606165927388552774443778601636463150652207936779357119888256103014675837");
BigInteger publicExponent = new BigInteger("65537");
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
List<PublicKey> publicKeyList = Converter.getRsaPublicKeysByJwk(jwk);
assertNotNull(publicKeyList);
assertEquals(publicKeyList.size(), 1);
assertEquals(publicKey, publicKeyList.get(0));
}
项目:JOSEPH
文件:ConverterTest.java
@Test
public void getRsaPublicKeyByPkcs8PemStringReturnsCorrectRsaPublicKeyObject() throws NoSuchAlgorithmException, InvalidKeySpecException, ParseException {
String pemString = "-----BEGIN PUBLIC KEY-----\n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqNyaO8jKmo/vfcFmxVNx\n"
+ "mJD4s+pJah9v/y7TxT1EGLLHZhAjZji7cZ+tyu5XDX6X9Mv3Cw5teQu9cdlTbdFp\n" + "rS9jRasnMlOfqI0V7jc7MOpa3n7AOeAYW9kFCL0qykKEs5B1f+F4zNAxp0hdE3eQ\n"
+ "KYCbCprXjHKF1CfH28C0Qk+GUtaRJbLaUybBoGvQ7vW/fdVUkuk3lOgnzF9dgrm0\n" + "8u11QLQpkF5glpC9ydiuWPNEKuOzTOGcgT3kA9XxliBLmuXO6OjDxxzzoDokMg82\n"
+ "rsQ9XQOE9E3MRF2THfeMyQW7lRO63DOPCM3OBboSlUJQxWFVlA+YbMMUU7G0LdFX\n" + "lQIDAQAB\n" + "-----END PUBLIC KEY-----\n";
RSAPublicKey publicKey = Converter.getRsaPublicKeyByPemString(pemString);
BigInteger modulus = new BigInteger(
"21316818368993447071015504638669801307527791584419862690177839595942029205894278985540228412443487713781149000078791190623276463454823320959362260326199842987421361386139414049320560418755520845179985115136181677185147622508697723189907444611574225122510119509110186633493415018035262172045096131517158872141869399939837654786497010314012641458269735824601371910054201921752066689022132849085664346125596962587379664190262614011733894298373034667307278544652193891973668886039046311943231827345356203903687328889718549241623336004630871090544516461376300794799815319108967915139001745002800408170876902995920807876501");
BigInteger publicExponent = new BigInteger("65537");
RSAPublicKey expectedPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
assertEquals(expectedPublicKey, publicKey);
}
项目:JOSEPH
文件:ConverterTest.java
@Test
public void getRsaPublicKeyByPkcs1PemStringReturnsCorrectRsaPublicKeyObject() throws NoSuchAlgorithmException, InvalidKeySpecException, ParseException {
String pemString = "-----BEGIN PUBLIC KEY-----\n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr0uGtoAbxPPnkWcuT31D\n"
+ "VX6skQBLs+FdxpcrnPi3DQg5ZVdUcp/vFeJts9HBBUjIXhhRqhqeauTNRrRpT6hZ\n" + "cZ0GwGajgIiGPyNxjlhkW1kXvKei//dr7z51A1x+Nzr/VTpsHD3luw/oL6gmFpeZ\n"
+ "fZ+cC5WlwrQGORDfOgjtIaKRMsbByU8nVay9OjalfcdHpAJzWm68ONo7eAEDSaf9\n" + "LqrdMvqY6pgMh4PdvpqSU1uhsd7VBKbWtEs7sj6PsH6qIAZv+AYtNGd0Fzhkj6xa\n"
+ "TBAY6Rl4S6Am6SCymZYCYVh3zbVFdD0zx6CoJixUzsWwSb+toq9IbZ6HEWjtlJVs\n" + "swIDAQAB\n" + "-----END PUBLIC KEY-----";
RSAPublicKey publicKey = Converter.getRsaPublicKeyByPemString(pemString);
BigInteger modulus = new BigInteger(
"22128946737323913239210052479333027707901510060102775675830991813349418659538199300647898430584144500806059458278321518777044762899512296866600872394644380219013320495156971514431190023600729602211122577883306928327035481763181383360484196857466673122026840292263234856687762092039930273840883706411057986999291723263528956058054902470342623926525220419403492184749748080083440782860930153041629788053392850350190345701856884676367792841834106393147716901597512639433053628947682648446566660847625123370647049602729290059736582541200917525808306486312868092094709254446973240693245640735124383753810943940731642145971");
BigInteger publicExponent = new BigInteger("65537");
RSAPublicKey expectedPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
assertEquals(expectedPublicKey, publicKey);
}
项目:adyen-api
文件:CSEUtil.java
public static Cipher rsaCipher(final String cseKeyText) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, IllegalArgumentException {
String[] cseKeyParts = cseKeyText.split("\\|");
if (cseKeyParts.length != 2) {
throw new InvalidKeyException("Invalid CSE Key: " + cseKeyText);
}
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
BigInteger keyComponent1, keyComponent2;
try {
keyComponent1 = new BigInteger(cseKeyParts[1].toLowerCase(Locale.getDefault()), 16);
keyComponent2 = new BigInteger(cseKeyParts[0].toLowerCase(Locale.getDefault()), 16);
} catch (NumberFormatException e) {
throw new InvalidKeyException("Invalid CSE Key: " + cseKeyText);
}
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(keyComponent1, keyComponent2);
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
Cipher result = Cipher.getInstance("RSA/None/PKCS1Padding");
result.init(Cipher.ENCRYPT_MODE, pubKey);
return result;
}
项目:MultimediaDesktop
文件:ConfigTools.java
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;
}
项目:SAMLRaider
文件:FakeBurpCertificateBuilder.java
@Override
public void generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
// https://github.com/bcgit/bc-java/blob/53d17ef99e30c6bd49e6eec9235e3eefca6a222d/pkix/src/test/java/org/bouncycastle/cert/test/CertTest.java
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(
"b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16));
RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec(new BigInteger(
"b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger(
"9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger(
"c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger(
"b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger(
"b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16));
KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
setPrivateKey(fact.generatePrivate(privKeySpec));
setPublicKey(fact.generatePublic(pubKeySpec));
}
项目:sc2gears
文件:PubKeyDecrypt.java
public static void main( final String[] args ) throws Exception {
final KeyFactory kf = KeyFactory.getInstance( "RSA" );
final BigInteger[] modExp = loadKey( "w:/pubkey.rsa" );
final PublicKey pubKey = kf.generatePublic( new RSAPublicKeySpec( modExp[ 0 ], modExp[ 1 ] ) );
final File encryptedFile = new File( "w:/encrypted.dat" );
final byte[] encrypted;
try ( final FileInputStream in = new FileInputStream( encryptedFile ) ) {
encrypted = new byte[ (int) encryptedFile.length() ];
in.read( encrypted );
}
final long start = System.nanoTime();
final Cipher cipher = Cipher.getInstance( "RSA" );
cipher.init( Cipher.DECRYPT_MODE, pubKey );
final byte[] decrypted = cipher.doFinal( encrypted );
final long end = System.nanoTime();
final String DOCUMENT = new String( decrypted, "UTF-8" );
System.out.println( "Successful decryption in " + ( ( end - start ) / 1000000L ) + " ms:" );
System.out.println( DOCUMENT );
}
项目:sc2gears
文件:RsaKeyPairGen.java
public static void main( final String[] args ) throws Exception {
final KeyPairGenerator kpGen = KeyPairGenerator.getInstance( "RSA" );
kpGen.initialize( KEY_SIZE_BITS );
final KeyPair kp = kpGen.generateKeyPair();
final PublicKey pubKey = kp.getPublic();
final PrivateKey privKey = kp.getPrivate();
if ( DEBUG ) {
System.out.println( pubKey .getAlgorithm() + " " + pubKey .getFormat() + " " + pubKey .getEncoded().length );
System.out.println( privKey.getAlgorithm() + " " + privKey.getFormat() + " " + privKey.getEncoded().length );
}
final KeyFactory kf = KeyFactory.getInstance( "RSA" );
final RSAPublicKeySpec pubKeySpec = kf.getKeySpec( pubKey , RSAPublicKeySpec .class );
final RSAPrivateKeySpec privKeySpec = kf.getKeySpec( privKey, RSAPrivateKeySpec.class );
if ( DEBUG ) {
System.out.println( pubKeySpec .getModulus() + " " + pubKeySpec .getPublicExponent() );
System.out.println( privKeySpec.getModulus() + " " + privKeySpec.getPrivateExponent() );
}
saveKey( pubKeySpec .getModulus(), pubKeySpec .getPublicExponent (), "w:/pubkey.rsa" );
saveKey( privKeySpec.getModulus(), privKeySpec.getPrivateExponent(), "w:/privkey.rsa" );
}
项目:infobip-open-jdk-8
文件: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);
}
项目:jdk8u-dev-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);
}
项目:spark-setup-android
文件:Crypto.java
static PublicKey buildPublicKey(byte[] rawBytes) throws CryptoException {
try {
//FIXME replacing X509EncodedKeySpec because of problem with 8.1
//Since 8.1 Bouncycastle cryptography was replaced with implementation from Conscrypt
//https://developer.android.com/about/versions/oreo/android-8.1.html
//either it's a bug in Conscrypt, our public key DER structure or use of X509EncodedKeySpec changed
//alternative needed as this adds expensive Spongycastle dependence
ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(rawBytes));
SubjectPublicKeyInfo info = SubjectPublicKeyInfo
.getInstance(new ASN1InputStream(bIn.readObject().getEncoded()).readObject());
DLSequence dlSequence = (DLSequence) ASN1Primitive.fromByteArray(info.getPublicKeyData().getBytes());
BigInteger modulus = ((ASN1Integer) dlSequence.getObjectAt(0)).getPositiveValue();
BigInteger exponent = ((ASN1Integer) dlSequence.getObjectAt(1)).getPositiveValue();
RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
KeyFactory kf = getRSAKeyFactory();
return kf.generatePublic(spec);
} catch (InvalidKeySpecException | IOException e) {
throw new CryptoException(e);
}
}
项目:ssh-agent-proxy
文件:TraditionalKeyParser.java
public static RSAPublicKeySpec parsePemPublicKey(String pemPublicKey) throws InvalidKeyException {
Matcher matcher = PUBLIC_KEY_PATTERN.matcher(pemPublicKey);
if (!matcher.matches()) {
throw new InvalidKeyException();
}
String pemKey = matcher.group(1);
BaseEncoding encoding = BaseEncoding.base64();
byte[] derKey = encoding.decode(pemKey);
ByteBuffer byteBuffer = ByteBuffer.wrap(derKey);
byteBuffer.order(ByteOrder.BIG_ENDIAN);
byte[] typeBytes = readVariableLengthOpaque(byteBuffer);
byte[] expBytes = readVariableLengthOpaque(byteBuffer);
byte[] modBytes = readVariableLengthOpaque(byteBuffer);
if (typeBytes == null || expBytes == null || modBytes == null) {
throw new InvalidKeyException();
}
String type = new String(typeBytes, Charsets.US_ASCII);
if (!type.equals(PUBLIC_KEY_TYPE)) {
throw new InvalidKeyException();
}
BigInteger exp = new BigInteger(expBytes);
BigInteger mod = new BigInteger(modBytes);
return new RSAPublicKeySpec(mod, exp);
}
项目:openid-connect
文件:RsaWebKey.java
@Override
public Key toJcaKey() throws GeneralSecurityException {
final BigInteger modulus = Encoding.base64urlDecodeUint(n);
final BigInteger publicExponent = Encoding.base64urlDecodeUint(e);
if (getUse() == KeyUse.sig || d == null) {
return KeyFactory.getInstance("RSA")
.generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
} else {
final BigInteger privateExponent = Encoding.base64urlDecodeUint(d);
final BigInteger primeP = Encoding.base64urlDecodeUint(p);
final BigInteger primeQ = Encoding.base64urlDecodeUint(q);
final BigInteger primeExponentP = Encoding.base64urlDecodeUint(dp);
final BigInteger primeExponentQ = Encoding.base64urlDecodeUint(dq);
final BigInteger crtCoefficent = Encoding.base64urlDecodeUint(qi);
return KeyFactory.getInstance("RSA")
.generatePrivate(new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponentQ, crtCoefficent));
}
}
项目:raccoon4
文件:GooglePlayAPI.java
public static PublicKey createKeyFromString(String str, byte[] bArr) {
try {
byte[] decode = Base64.decode(str, 0);
int readInt = readInt(decode, 0);
byte[] obj = new byte[readInt];
System.arraycopy(decode, 4, obj, 0, readInt);
BigInteger bigInteger = new BigInteger(1, obj);
int readInt2 = readInt(decode, readInt + 4);
byte[] obj2 = new byte[readInt2];
System.arraycopy(decode, readInt + 8, obj2, 0, readInt2);
BigInteger bigInteger2 = new BigInteger(1, obj2);
decode = MessageDigest.getInstance("SHA-1").digest(decode);
bArr[0] = (byte) 0;
System.arraycopy(decode, 0, bArr, 1, 4);
return KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(bigInteger, bigInteger2));
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
项目:raccoon4
文件:Identity.java
private static PublicKey createKeyFromString(String str, byte[] bArr)
throws NoSuchAlgorithmException, InvalidKeySpecException {
byte[] decode = Base64.decode(str, 0);
int readInt = readInt(decode, 0);
byte[] obj = new byte[readInt];
System.arraycopy(decode, 4, obj, 0, readInt);
BigInteger bigInteger = new BigInteger(1, obj);
int readInt2 = readInt(decode, readInt + 4);
byte[] obj2 = new byte[readInt2];
System.arraycopy(decode, readInt + 8, obj2, 0, readInt2);
BigInteger bigInteger2 = new BigInteger(1, obj2);
decode = MessageDigest.getInstance("SHA-1").digest(decode);
bArr[0] = (byte) 0;
System.arraycopy(decode, 0, bArr, 1, 4);
return KeyFactory.getInstance("RSA").generatePublic(
new RSAPublicKeySpec(bigInteger, bigInteger2));
}
项目:haox
文件:PKCS8Key.java
public PublicKey getPublicKey() throws GeneralSecurityException {
if (privateKey instanceof DSAPrivateKey) {
DSAPrivateKey dsa = (DSAPrivateKey) privateKey;
DSAParams params = dsa.getParams();
BigInteger g = params.getG();
BigInteger p = params.getP();
BigInteger q = params.getQ();
BigInteger x = dsa.getX();
BigInteger y = q.modPow( x, p );
DSAPublicKeySpec dsaKeySpec = new DSAPublicKeySpec(y, p, q, g);
return KeyFactory.getInstance("DSA").generatePublic(dsaKeySpec);
} else if (privateKey instanceof RSAPrivateCrtKey) {
RSAPrivateCrtKey rsa = (RSAPrivateCrtKey) privateKey;
RSAPublicKeySpec rsaKeySpec = new RSAPublicKeySpec(
rsa.getModulus(),
rsa.getPublicExponent()
);
return KeyFactory.getInstance("RSA").generatePublic(rsaKeySpec);
} else {
throw new GeneralSecurityException("Not an RSA or DSA key");
}
}
项目:crtauth-java
文件:TraditionalKeyParser.java
public static RSAPublicKeySpec parsePemPublicKey(String pemPublicKey) throws InvalidKeyException {
Matcher matcher = PUBLIC_KEY_PATTERN.matcher(pemPublicKey);
if (!matcher.matches()) {
throw new InvalidKeyException();
}
String pemKey = matcher.group(1);
BaseEncoding encoding = BaseEncoding.base64();
byte[] derKey = encoding.decode(pemKey);
ByteBuffer byteBuffer = ByteBuffer.wrap(derKey);
byteBuffer.order(ByteOrder.BIG_ENDIAN);
byte[] typeBytes = readVariableLengthOpaque(byteBuffer);
byte[] expBytes = readVariableLengthOpaque(byteBuffer);
byte[] modBytes = readVariableLengthOpaque(byteBuffer);
if (typeBytes == null || expBytes == null || modBytes == null) {
throw new InvalidKeyException();
}
String type = new String(typeBytes, Charsets.US_ASCII);
if (!type.equals(PUBLIC_KEY_TYPE)) {
throw new InvalidKeyException();
}
BigInteger exp = new BigInteger(expBytes);
BigInteger mod = new BigInteger(modBytes);
return new RSAPublicKeySpec(mod, exp);
}
项目:crtauth-java
文件:CrtAuthServerTest.java
@Before
public void setup() throws Exception {
keyProvider = new InMemoryKeyProvider();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec noaPublicKeySpec = TraditionalKeyParser.parsePemPublicKey(NOA_PUBLIC_KEY);
RSAPublicKey noaPublicKey = (RSAPublicKey) keyFactory.generatePublic(noaPublicKeySpec);
keyProvider.putKey("noa", noaPublicKey);
RSAPublicKeySpec publicKeySpec = TraditionalKeyParser.parsePemPublicKey(PUBLIC_KEY);
RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
keyProvider.putKey("test", publicKey);
crtAuthServer = new CrtAuthServer.Builder()
.setServerName(SERVER_NAME)
.setSecret("server_secret".getBytes())
.setKeyProvider(keyProvider)
.build();
RSAPrivateKeySpec privateKeySpec = TraditionalKeyParser.parsePemPrivateKey(PRIVATE_KEY);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
Signer signer = new SingleKeySigner(privateKey);
crtAuthClient = new CrtAuthClient(signer, SERVER_NAME);
}
项目:crtauth-java
文件:CrtAuthServerTest.java
@Test
public void testCreateChallengeMultipleKeyProviders() throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
InMemoryKeyProvider keyProvider1 = new InMemoryKeyProvider();
RSAPublicKeySpec publicKeySpec = TraditionalKeyParser.parsePemPublicKey(PUBLIC_KEY);
RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
keyProvider1.putKey("test", publicKey);
InMemoryKeyProvider keyProvider2 = new InMemoryKeyProvider();
RSAPublicKeySpec noaPublicKeySpec = TraditionalKeyParser.parsePemPublicKey(NOA_PUBLIC_KEY);
RSAPublicKey noaPublicKey = (RSAPublicKey) keyFactory.generatePublic(noaPublicKeySpec);
keyProvider2.putKey("noa", noaPublicKey);
byte[] serverSecret = "spotify".getBytes();
CrtAuthServer crtAuthServer = new CrtAuthServer.Builder()
.setServerName("server_name")
.setSecret(serverSecret)
.addKeyProvider(keyProvider1)
.addKeyProvider(keyProvider2)
.build();
String challenge = crtAuthServer.createChallenge(CrtAuthClient.createRequest("noa"));
Fingerprint expectedFingerprint = new Fingerprint(decode("-6Hqb9N5"));
Assert.assertTrue(extractFingerprint(challenge).equals(expectedFingerprint));
}
项目:tor-research-framework
文件:TorCrypto.java
public static RSAPublicKey asn1GetPrivateKeyPublic(byte[] rsapkbuf) {
ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(rsapkbuf));
try {
DLSequence obj = (DLSequence) bIn.readObject();
ASN1Integer mod = (ASN1Integer) obj.getObjectAt(1);
ASN1Integer pubExp = (ASN1Integer) obj.getObjectAt(2);
ASN1Integer privExp = (ASN1Integer) obj.getObjectAt(3);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(mod.getValue(), pubExp.getValue()));
return pubKey;
} catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}