Java 类java.security.interfaces.RSAPublicKey 实例源码
项目:plugins-sdk-java
文件:SSOFacade.java
/**
* Initialize this component by building up the consumer for JWT using the
* pre-configured secret
*
* @param rsaPublicKey the RSA public key to be used for verification.
*
* @return Fluent interface.
*/
SSOFacade initialize(final RSAPublicKey rsaPublicKey) {
if (logger.isDebugEnabled()) {
logger.debug("Initializing single-sign-on manager SSOFacade. ");
}
Objects.requireNonNull(rsaPublicKey);
// Build up the algorithm constraints by only accepting RSA_USING_SHA256.
final AlgorithmConstraints algorithmConstraints = new AlgorithmConstraints(
AlgorithmConstraints.ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256);
this.jwtConsumer = new JwtConsumerBuilder()
.setJwsAlgorithmConstraints(algorithmConstraints)
.setSkipDefaultAudienceValidation()
.setVerificationKey(rsaPublicKey)
.setRequireExpirationTime()
.setRequireNotBefore()
.setRequireIssuedAt()
.build();
return this;
}
项目:jeesupport
文件:RSAUtils.java
/**
* 初始化密钥
*
* @param byte[]
* _arg 种子
* @return
* @throws Exception
*/
public static Map< String , Key > s_genkeys_map( byte[] _arg ) throws Exception {
// 实例化密钥对生成器
KeyPairGenerator key_pair_generator = KeyPairGenerator.getInstance( KEY_ALGORITHM_RSA );
// 初始化密钥对生成器
key_pair_generator.initialize( KEY_SIZE , new SecureRandom( _arg ) );
// 生成密钥对
KeyPair key_pair = key_pair_generator.generateKeyPair();
// 公钥
RSAPublicKey public_key = (RSAPublicKey) key_pair.getPublic();
// 私钥
RSAPrivateKey private_key = (RSAPrivateKey) key_pair.getPrivate();
// 封装密钥
Map< String , Key > key_map = new HashMap< String , Key >( 2 );
key_map.put( RSA_PUBLIC_KEY , public_key );
key_map.put( RSA_PRIVATE_KEY , private_key );
return key_map;
}
项目:L2J-Global
文件:GameServerThread.java
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();
}
项目:GitHub
文件:PubkeyUtils.java
/**
* @param pair KeyPair to convert to an OpenSSH public key
* @return OpenSSH-encoded pubkey
*/
public static byte[] extractOpenSSHPublic(KeyPair pair) {
try {
PublicKey pubKey = pair.getPublic();
if (pubKey instanceof RSAPublicKey) {
return RSASHA1Verify.encodeSSHRSAPublicKey((RSAPublicKey) pubKey);
} else if (pubKey instanceof DSAPublicKey) {
return DSASHA1Verify.encodeSSHDSAPublicKey((DSAPublicKey) pubKey);
} else if (pubKey instanceof ECPublicKey) {
return ECDSASHA2Verify.encodeSSHECDSAPublicKey((ECPublicKey) pubKey);
} else if (pubKey instanceof EdDSAPublicKey) {
return Ed25519Verify.encodeSSHEd25519PublicKey((EdDSAPublicKey) pubKey);
} else {
return null;
}
} catch (IOException e) {
return null;
}
}
项目:openjdk-jdk10
文件:NewSize7.java
public static void main(String[] args) throws Exception {
String FILE = "newsize7-ks";
new File(FILE).delete();
sun.security.tools.keytool.Main.main(("-debug -genkeypair -keystore " +
FILE +
" -alias a -dname cn=c -storepass changeit" +
" -keypass changeit -keyalg rsa").split(" "));
KeyStore ks = KeyStore.getInstance("JKS");
try (FileInputStream fin = new FileInputStream(FILE)) {
ks.load(fin, "changeit".toCharArray());
}
Files.delete(Paths.get(FILE));
RSAPublicKey r = (RSAPublicKey)ks.getCertificate("a").getPublicKey();
if (r.getModulus().bitLength() != 2048) {
throw new Exception("Bad keysize");
}
X509Certificate x = (X509Certificate)ks.getCertificate("a");
if (!x.getSigAlgName().equals("SHA256withRSA")) {
throw new Exception("Bad sigalg");
}
}
项目:javaOIDCMsg
文件:RSAAlgorithmTest.java
@Test
public void shouldDoRSA512SigningWithBothKeys() throws Exception {
Algorithm algorithm = Algorithm.RSA512((RSAPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA"), (RSAPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA"));
String jwtContent = String.format("%s.%s", RS512Header, auth0IssPayload);
byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
byte[] signatureBytes = algorithm.sign(contentBytes);
String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
String token = String.format("%s.%s", jwtContent, jwtSignature);
String expectedSignature = "THIPVYzNZ1Yo_dm0k1UELqV0txs3SzyMopCyHcLXOOdgYXF4MlGvBqu0CFvgSga72Sp5LpuC1Oesj40v_QDsp2GTGDeWnvvcv_eo-b0LPSpmT2h1Ibrmu-z70u2rKf28pkN-AJiMFqi8sit2kMIp1bwIVOovPvMTQKGFmova4Xwb3G526y_PeLlflW1h69hQTIVcI67ACEkAC-byjDnnYIklA-B4GWcggEoFwQRTdRjAUpifA6HOlvnBbZZlUd6KXwEydxVS-eh1odwPjB2_sfbyy5HnLsvNdaniiZQwX7QbwLNT4F72LctYdHHM1QCrID6bgfgYp9Ij9CRX__XDEA";
assertThat(signatureBytes, is(notNullValue()));
assertThat(jwtSignature, is(expectedSignature));
JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
DecodedJWT decoded = jwt.decode(token);
algorithm.verify(decoded, EncodeType.Base64);
}
项目:javaOIDCMsg
文件:RSAAlgorithmTest.java
@Test
public void shouldThrowWhenTheSignatureIsNotPrepared() throws Exception {
exception.expect(AlgorithmMismatchException.class);
exception.expectMessage("The provided Algorithm doesn't match the one defined in the JWT's Header.");
CryptoHelper crypto = mock(CryptoHelper.class);
when(crypto.verifySignatureFor(anyString(), any(PublicKey.class), any(byte[].class), any(byte[].class)))
.thenThrow(SignatureException.class);
RSAPublicKey publicKey = mock(RSAPublicKey.class);
RSAPrivateKey privateKey = mock(RSAPrivateKey.class);
RSAKeyProvider provider = RSAAlgorithm.providerForKeys(publicKey, privateKey);
Algorithm algorithm = new RSAAlgorithm(crypto, "some-alg", "some-algorithm", provider);
String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.dxXF3MdsyW-AuvwJpaQtrZ33fAde9xWxpLIg9cO2tMLH2GSRNuLAe61KsJusZhqZB9Iy7DvflcmRz-9OZndm6cj_ThGeJH2LLc90K83UEvvRPo8l85RrQb8PcanxCgIs2RcZOLygERizB3pr5icGkzR7R2y6zgNCjKJ5_NJ6EiZsGN6_nc2PRK_DbyY-Wn0QDxIxKoA5YgQJ9qafe7IN980pXvQv2Z62c3XR8dYuaXBqhthBj-AbaFHEpZapN-V-TmuLNzR2MCB6Xr7BYMuCaqWf_XU8og4XNe8f_8w9Wv5vvgqMM1KhqVpG5VdMJv4o_L4NoCROHhtUQSLRh2M9cA";
JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
DecodedJWT decoded = jwt.decode(token);
algorithm.verify(decoded, EncodeType.Base64);
}
项目:L2jBrasil
文件:BlowFishKey.java
/**
* @param blowfishKey
* @param publicKey
*/
public BlowFishKey(byte[] blowfishKey, RSAPublicKey publicKey)
{
writeC(0x00);
byte[] encrypted =null;
try
{
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/nopadding");
rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey);
encrypted = rsaCipher.doFinal(blowfishKey);
}
catch(GeneralSecurityException e)
{
_log.severe("Error While encrypting blowfish key for transmision (Crypt error)");
e.printStackTrace();
}
writeD(encrypted.length);
writeB(encrypted);
}
项目:javaOIDCMsg
文件:RSAAlgorithmTest.java
@Test
public void shouldDoRSA512SigningWithProvidedPrivateKey() throws Exception {
RSAKeyProvider provider = mock(RSAKeyProvider.class);
PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA");
PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA");
when(provider.getPrivateKey()).thenReturn((RSAPrivateKey) privateKey);
when(provider.getPublicKeyById(null)).thenReturn((RSAPublicKey) publicKey);
Algorithm algorithm = Algorithm.RSA512(provider);
String jwtContent = String.format("%s.%s", RS512Header, auth0IssPayload);
byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
byte[] signatureBytes = algorithm.sign(contentBytes);
String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
String token = String.format("%s.%s", jwtContent, jwtSignature);
assertThat(signatureBytes, is(notNullValue()));
JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
DecodedJWT decoded = jwt.decode(token);
algorithm.verify(decoded, EncodeType.Base64);
}
项目:javaOIDCMsg
文件:RSAAlgorithmTest.java
@Test
public void shouldThrowWhenMacAlgorithmDoesNotExists() throws Exception {
exception.expect(AlgorithmMismatchException.class);
exception.expectMessage("The provided Algorithm doesn't match the one defined in the JWT's Header.");
CryptoHelper crypto = mock(CryptoHelper.class);
when(crypto.verifySignatureFor(anyString(), any(PublicKey.class), any(byte[].class), any(byte[].class)))
.thenThrow(NoSuchAlgorithmException.class);
RSAPublicKey publicKey = mock(RSAPublicKey.class);
RSAPrivateKey privateKey = mock(RSAPrivateKey.class);
RSAKeyProvider provider = RSAAlgorithm.providerForKeys(publicKey, privateKey);
Algorithm algorithm = new RSAAlgorithm(crypto, "some-alg", "some-algorithm", provider);
String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.dxXF3MdsyW-AuvwJpaQtrZ33fAde9xWxpLIg9cO2tMLH2GSRNuLAe61KsJusZhqZB9Iy7DvflcmRz-9OZndm6cj_ThGeJH2LLc90K83UEvvRPo8l85RrQb8PcanxCgIs2RcZOLygERizB3pr5icGkzR7R2y6zgNCjKJ5_NJ6EiZsGN6_nc2PRK_DbyY-Wn0QDxIxKoA5YgQJ9qafe7IN980pXvQv2Z62c3XR8dYuaXBqhthBj-AbaFHEpZapN-V-TmuLNzR2MCB6Xr7BYMuCaqWf_XU8og4XNe8f_8w9Wv5vvgqMM1KhqVpG5VdMJv4o_L4NoCROHhtUQSLRh2M9cA";
JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
DecodedJWT decoded = jwt.decode(token);
algorithm.verify(decoded, EncodeType.Base64);
}
项目:ipack
文件:JCERSAPublicKey.java
public boolean equals(Object o)
{
if (o == this)
{
return true;
}
if (!(o instanceof RSAPublicKey))
{
return false;
}
RSAPublicKey key = (RSAPublicKey)o;
return getModulus().equals(key.getModulus())
&& getPublicExponent().equals(key.getPublicExponent());
}
项目:ipack
文件:BCRSAPublicKey.java
public boolean equals(Object o)
{
if (o == this)
{
return true;
}
if (!(o instanceof RSAPublicKey))
{
return false;
}
RSAPublicKey key = (RSAPublicKey)o;
return getModulus().equals(key.getModulus())
&& getPublicExponent().equals(key.getPublicExponent());
}
项目:iBase4J-Common
文件:RSACoder.java
/**
* 初始化密钥
*
* @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;
}
项目:ProyectoPacientes
文件:ExportControlled.java
public static RSAPublicKey decodeRSAPublicKey(String key, ExceptionInterceptor interceptor) throws SQLException {
try {
if (key == null) {
throw new SQLException("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);
KeyFactory kf = KeyFactory.getInstance("RSA");
return (RSAPublicKey) kf.generatePublic(spec);
} catch (Exception ex) {
throw SQLError.createSQLException("Unable to decode public key", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, ex, interceptor);
}
}
项目:Selector
文件:RSASecurityUtils.java
/**
* 公钥加密
*
* @param data
* @param publicKey
* @return
* @throws Exception
*/
public static String encryptByPublicKey(String data, RSAPublicKey publicKey)
throws Exception {
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 模长
int key_len = publicKey.getModulus().bitLength() / 8;
// 加密数据长度 <= 模长-11
String[] datas = splitString(data, key_len - 11);
String mi = "";
//如果明文长度大于模长-11则要分组加密
for (String s : datas) {
mi += bcd2Str(cipher.doFinal(s.getBytes()));
}
return mi;
}
项目:javaOIDCMsg
文件:RSAAlgorithm.java
static RSAKeyProvider providerForKeys(final RSAPublicKey publicKey, final RSAPrivateKey privateKey) {
if (publicKey == null && privateKey == null) {
throw new IllegalArgumentException("Both provided Keys cannot be null.");
}
return new RSAKeyProvider() {
@Override
public RSAPublicKey getPublicKeyById(String keyId) {
return publicKey;
}
@Override
public RSAPrivateKey getPrivateKey() {
return privateKey;
}
@Override
public String getPrivateKeyId() {
return null;
}
};
}
项目:javaOIDCMsg
文件:RSAAlgorithmTest.java
@Test
public void shouldDoRSA384SigningWithProvidedPrivateKey() throws Exception {
RSAKeyProvider provider = mock(RSAKeyProvider.class);
PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA");
PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA");
when(provider.getPrivateKey()).thenReturn((RSAPrivateKey) privateKey);
when(provider.getPublicKeyById(null)).thenReturn((RSAPublicKey) publicKey);
Algorithm algorithm = Algorithm.RSA384(provider);
String jwtContent = String.format("%s.%s", RS384Header, auth0IssPayload);
byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
byte[] signatureBytes = algorithm.sign(contentBytes);
String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
String token = String.format("%s.%s", jwtContent, jwtSignature);
assertThat(signatureBytes, is(notNullValue()));
JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
DecodedJWT decoded = jwt.decode(token);
algorithm.verify(decoded, EncodeType.Base64);
}
项目:springboot-training
文件:RSACoder.java
/**
* 初始化密钥
*
* @return
* @throws Exception
*/
public static Map<String, Key> initKey() {
try {
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, Key> keyMap = new HashMap<String, Key>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("初始化密钥出错 " + e.getMessage());
}
}
项目:mycat-src-1.6.1-RELEASE
文件:DecryptUtil.java
public static String decrypt(PublicKey publicKey, String cipherText)
throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
try {
cipher.init(Cipher.DECRYPT_MODE, publicKey);
} catch (InvalidKeyException e) {
// 因为 IBM JDK 不支持私钥加密, 公钥解密, 所以要反转公私钥
// 也就是说对于解密, 可以通过公钥的参数伪造一个私钥对象欺骗 IBM JDK
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
RSAPrivateKeySpec spec = new RSAPrivateKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
Key fakePrivateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
cipher = Cipher.getInstance("RSA"); //It is a stateful object. so we need to get new one.
cipher.init(Cipher.DECRYPT_MODE, fakePrivateKey);
}
if (cipherText == null || cipherText.length() == 0) {
return cipherText;
}
byte[] cipherBytes = Base64.base64ToByteArray(cipherText);
byte[] plainBytes = cipher.doFinal(cipherBytes);
return new String(plainBytes);
}
项目:dble
文件:DecryptUtil.java
public static String decrypt(PublicKey publicKey, String cipherText)
throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
try {
cipher.init(Cipher.DECRYPT_MODE, publicKey);
} catch (InvalidKeyException e) {
// IBM JDK not support Private key encryption, public key decryption
// so fake an PrivateKey for it
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
RSAPrivateKeySpec spec = new RSAPrivateKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
Key fakePrivateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
cipher = Cipher.getInstance("RSA"); //It is a stateful object. so we need to get new one.
cipher.init(Cipher.DECRYPT_MODE, fakePrivateKey);
}
if (cipherText == null || cipherText.length() == 0) {
return cipherText;
}
byte[] cipherBytes = Base64.base64ToByteArray(cipherText);
byte[] plainBytes = cipher.doFinal(cipherBytes);
return new String(plainBytes);
}
项目:the-vigilantes
文件:ExportControlled.java
public static RSAPublicKey decodeRSAPublicKey(String key, ExceptionInterceptor interceptor) throws SQLException {
try {
if (key == null) {
throw new SQLException("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);
KeyFactory kf = KeyFactory.getInstance("RSA");
return (RSAPublicKey) kf.generatePublic(spec);
} catch (Exception ex) {
throw SQLError.createSQLException("Unable to decode public key", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, ex, interceptor);
}
}
项目:xitk
文件:IaikP11Identity.java
IaikP11Identity(IaikP11Slot slot, P11EntityIdentifier identityId, PrivateKey privateKey,
PublicKey publicKey, X509Certificate[] certificateChain) {
super(slot, identityId, publicKey, certificateChain);
this.signingKey = ParamUtil.requireNonNull("privateKey", privateKey);
int keyBitLen = signatureKeyBitLength();
if (publicKey instanceof RSAPublicKey) {
expectedSignatureLen = (keyBitLen + 7) / 8;
} else if (publicKey instanceof ECPublicKey) {
expectedSignatureLen = (keyBitLen + 7) / 8 * 2;
} else if (publicKey instanceof DSAPublicKey) {
expectedSignatureLen = (keyBitLen + 7) / 8 * 2;
} else {
throw new IllegalArgumentException(
"currently only RSA, DSA and EC public key are supported, but not "
+ this.publicKey.getAlgorithm()
+ " (class: " + publicKey.getClass().getName() + ")");
}
}
项目:xitk
文件:P11PrivateKey.java
public P11PrivateKey(P11CryptService p11CryptService, P11EntityIdentifier identityId)
throws P11TokenException {
this.p11CryptService = ParamUtil.requireNonNull("identityId", p11CryptService);
this.identityId = ParamUtil.requireNonNull("entityId", identityId);
this.publicKey = p11CryptService.getIdentity(identityId).publicKey();
if (this.publicKey instanceof RSAPublicKey) {
algorithm = "RSA";
keysize = ((RSAPublicKey) publicKey).getModulus().bitLength();
} else if (this.publicKey instanceof DSAPublicKey) {
algorithm = "DSA";
keysize = ((DSAPublicKey) publicKey).getParams().getP().bitLength();
} else if (this.publicKey instanceof ECPublicKey) {
algorithm = "EC";
keysize = ((ECPublicKey) publicKey).getParams().getCurve().getField().getFieldSize();
} else {
throw new P11TokenException("unknown public key: " + publicKey);
}
}
项目:javaOIDCMsg
文件:RSAAlgorithmTest.java
@Test
public void shouldThrowOnSignWhenTheSignatureIsNotPrepared() throws Exception {
exception.expect(SignatureGenerationException.class);
exception.expectMessage("The Token's Signature couldn't be generated when signing using the Algorithm: some-algorithm");
exception.expectCause(isA(SignatureException.class));
CryptoHelper crypto = mock(CryptoHelper.class);
when(crypto.createSignatureFor(anyString(), any(PrivateKey.class), any(byte[].class)))
.thenThrow(SignatureException.class);
RSAPublicKey publicKey = mock(RSAPublicKey.class);
RSAPrivateKey privateKey = mock(RSAPrivateKey.class);
RSAKeyProvider provider = RSAAlgorithm.providerForKeys(publicKey, privateKey);
Algorithm algorithm = new RSAAlgorithm(crypto, "some-alg", "some-algorithm", provider);
algorithm.sign(RS256Header.getBytes(StandardCharsets.UTF_8));
}
项目:mumu
文件:RSACoder.java
/**
* 初始化密钥
*
* @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;
}
项目:azure-libraries-for-java
文件:TestContainerService.java
private String getSshKey() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair=keyPairGenerator.generateKeyPair();
RSAPublicKey publicKey=(RSAPublicKey)keyPair.getPublic();
ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(byteOs);
dos.writeInt("ssh-rsa".getBytes().length);
dos.write("ssh-rsa".getBytes());
dos.writeInt(publicKey.getPublicExponent().toByteArray().length);
dos.write(publicKey.getPublicExponent().toByteArray());
dos.writeInt(publicKey.getModulus().toByteArray().length);
dos.write(publicKey.getModulus().toByteArray());
String publicKeyEncoded = new String(
Base64.encodeBase64(byteOs.toByteArray()));
return "ssh-rsa " + publicKeyEncoded + " ";
}
项目:javaOIDCMsg
文件:RSAAlgorithmTest.java
@Test
public void shouldDoRSA256SigningWithProvidedPrivateKey() throws Exception {
RSAKeyProvider provider = mock(RSAKeyProvider.class);
PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA");
PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA");
when(provider.getPrivateKey()).thenReturn((RSAPrivateKey) privateKey);
when(provider.getPublicKeyById(null)).thenReturn((RSAPublicKey) publicKey);
Algorithm algorithm = Algorithm.RSA256(provider);
String jwtContent = String.format("%s.%s", RS256Header, auth0IssPayload);
byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
byte[] signatureBytes = algorithm.sign(contentBytes);
String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
String token = String.format("%s.%s", jwtContent, jwtSignature);
assertThat(signatureBytes, is(notNullValue()));
JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
DecodedJWT decoded = jwt.decode(token);
algorithm.verify(decoded, EncodeType.Base64);
}
项目:lams
文件:KeyInfoHelper.java
/**
* Builds an {@link RSAKeyValue} XMLObject from the Java security RSA public key type.
*
* @param rsaPubKey a native Java {@link RSAPublicKey}
* @return an {@link RSAKeyValue} XMLObject
*/
public static RSAKeyValue buildRSAKeyValue(RSAPublicKey rsaPubKey) {
XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
RSAKeyValue rsaKeyValue = (RSAKeyValue) builderFactory
.getBuilder(RSAKeyValue.DEFAULT_ELEMENT_NAME)
.buildObject(RSAKeyValue.DEFAULT_ELEMENT_NAME);
Modulus modulus = (Modulus) builderFactory
.getBuilder(Modulus.DEFAULT_ELEMENT_NAME)
.buildObject(Modulus.DEFAULT_ELEMENT_NAME);
Exponent exponent = (Exponent) builderFactory
.getBuilder(Exponent.DEFAULT_ELEMENT_NAME)
.buildObject(Exponent.DEFAULT_ELEMENT_NAME);
modulus.setValueBigInt(rsaPubKey.getModulus());
rsaKeyValue.setModulus(modulus);
exponent.setValueBigInt(rsaPubKey.getPublicExponent());
rsaKeyValue.setExponent(exponent);
return rsaKeyValue;
}
项目:xitikit-blue
文件:SimpleB2CAuthenticationService.java
/**
* Attempts to get an RSAPublicKey for the given policy.
*
* @param keyId the key ID to fetch
* @param policy the policy the key belongs to
*
* @return the key or null if it could not be fetched
*/
@Nullable
private RSAPublicKey rsaPublicKey(
@Nonnull final String keyId,
@Nonnull final String policy){
try{
JsonNode kidNode = kidForKeyId(
keysForPolicy(policy),
keyId
);
return parseKey(
modulus(kidNode),
exponent(kidNode)
);
}catch(RestClientException | NullPointerException x){
log.error("Error retrieving RSA keys for policy [" + policy + "]: " + x.getMessage(), x);
}
return null;
}
项目:javaOIDCMsg
文件:RSAAlgorithmTest.java
@Test
public void shouldDoRSA384SigningWithBothKeys() throws Exception {
Algorithm algorithm = Algorithm.RSA384((RSAPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA"), (RSAPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA"));
String jwtContent = String.format("%s.%s", RS384Header, auth0IssPayload);
byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
byte[] signatureBytes = algorithm.sign(contentBytes);
String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
String token = String.format("%s.%s", jwtContent, jwtSignature);
String expectedSignature = "Jx1PaTBnjd_U56MNjifFcY7w9ImDbseg0y8Ijr2pSiA1_wzQb_wy9undaWfzR5YqdIAXvjS8AGuZUAzIoTG4KMgOgdVyYDz3l2jzj6wI-lgqfR5hTy1w1ruMUQ4_wobpdxAiJ4fEbg8Mi_GljOiCO-P1HilxKnpiOJZidR8MQGwTInsf71tOUkK4x5UsdmUueuZbaU-CL5kPnRfXmJj9CcdxZbD9oMlbo23dwkP5BNMrS2LwGGzc9C_-ypxrBIOVilG3WZxcSmuG86LjcZbnL6LBEfph5NmKBgQav147uipb_7umBEr1m2dYiB_9u606n3bcoo3rnsYYK_Xfi1GAEQ";
assertThat(signatureBytes, is(notNullValue()));
assertThat(jwtSignature, is(expectedSignature));
JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
DecodedJWT decoded = jwt.decode(token);
algorithm.verify(decoded, EncodeType.Base64);
}
项目:iBase4J
文件:RSACoder.java
/**
* 初始化密钥
*
* @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;
}
项目:android-rsa
文件:RSAProvider.java
/**
*
* 生成KeyPair
* @return
* @throws Exception
*/
public static Map<String, Object> generateKeyPair() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(KEYSIZE);
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
BigInteger modules = privateKey.getModulus();
Map<String, Object> keys = new HashMap<String, Object>(3);
keys.put(PUBLIC_KEY, publicKey);
keys.put(PRIVATE_KEY, privateKey);
keys.put(MODULES, modules);
return keys;
}
项目:GitHub
文件:Codec.java
/**
* 初始化密钥
*
* @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;
}
项目:openjdk-jdk10
文件:KeySizeTest.java
/**
* @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;
}
项目:GroupControlDroidClient
文件:RSAUtil.java
/**
* 生成公钥和私钥
*
* @throws NoSuchAlgorithmException
*
*/
public static HashMap<String, Object> getKeys()
throws NoSuchAlgorithmException {
HashMap<String, Object> map = new HashMap<String, Object>();
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024,new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
map.put("public", publicKey);
map.put("private", privateKey);
return map;
}
项目:bubichain-sdk-java
文件:RSAUtils.java
public static RSAKeyPair generateKey512(){
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALG_RSA);
keyPairGen.initialize(512, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
return new RSAKeyPair(publicKey.getEncoded(), privateKey.getEncoded());
} catch (NoSuchAlgorithmException e) {
throw new KeyGenerationException(e.getMessage(), e);
}
}
项目:MyCreditCardDemo
文件:RSAUtils.java
public static void loadPublicKey(String pubKey) {
try {
byte[] buffer = Base64.decode(pubKey, Base64.DEFAULT);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
}
}
项目:TIIEHenry-Android-SDK
文件:RSAUtils.java
/**
* 生成公钥
*
* @param modulus
* @param publicExponent
* @return
*/
private static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) {
try {
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(
1, modulus), new BigInteger(1, publicExponent));
KeyFactory keyFac = KeyFactory.getInstance(KEY_ALGORITHM);
return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
} catch (Exception e) {
throw new RuntimeException("Error when generate rsaPubblicKey, errmsg: " + e.getMessage(), e);
}
}
项目:ISO9796SignerVerifier
文件:App.java
private static String verify() throws Exception {
RSAEngine engine = new RSAEngine();
Digest digest = new SHA1Digest();
RSAPublicKey publicKey = (RSAPublicKey) getPublic(publicKeyFilename);
BigInteger big = ((RSAKey) publicKey).getModulus();
RSAKeyParameters rsaPublic = new RSAKeyParameters(false, big, publicKey.getPublicExponent());
ISO9796d2Signer verifier = new ISO9796d2Signer(engine, digest, true);
verifier.init(false, rsaPublic); // false for verify
if (!verifier.verifySignature(signature)) {
System.err.println("Signature was modified, could not verify correctness!");
return "";
}
String recoveredMessage = "";
try {
if (verifier.hasFullMessage()) {
verifier.updateWithRecoveredMessage(signature);
}
byte[] message = verifier.getRecoveredMessage();
recoveredMessage = new String(message, "UTF-8");
} catch (Exception exception) {
System.err.println("Recover failed!");
}
return recoveredMessage;
}
项目:quilt
文件:RsaSha256Fulfillment.java
/**
* Constructs an instance of the fulfillment.
*
* @param publicKey An {@link RSAPublicKey} to be used with this fulfillment.
* @param signature A byte array that contains a binary representation of the signature associated
* with this fulfillment.
*/
public RsaSha256Fulfillment(final RSAPublicKey publicKey, final byte[] signature) {
super(RSA_SHA256);
Objects.requireNonNull(publicKey, "PublicKey must not be null!");
Objects.requireNonNull(signature, "Signature must not be null!");
this.publicKey = publicKey;
this.signature = Arrays.copyOf(signature, signature.length);
this.signatureBase64Url = Base64.getUrlEncoder().encodeToString(signature);
this.condition = new RsaSha256Condition(publicKey);
}