本文整理汇总了Java中java.security.spec.RSAPrivateKeySpec类的典型用法代码示例。如果您正苦于以下问题:Java RSAPrivateKeySpec类的具体用法?Java RSAPrivateKeySpec怎么用?Java RSAPrivateKeySpec使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
RSAPrivateKeySpec类属于java.security.spec包,在下文中一共展示了RSAPrivateKeySpec类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createPrivateKey
import java.security.spec.RSAPrivateKeySpec; //导入依赖的package包/类
/**
* 从hex string 生成私钥
*
* @param stringN
* @param stringD
* @return 构造好的私钥
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey createPrivateKey(String stringN, String stringD)
throws NoSuchAlgorithmException, InvalidKeySpecException {
try {
BigInteger N = new BigInteger(stringN, 16); // hex base
BigInteger D = new BigInteger(stringD, 16); // hex base
RSAPrivateKeySpec spec = new RSAPrivateKeySpec(N, D);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
示例2: decrypt
import java.security.spec.RSAPrivateKeySpec; //导入依赖的package包/类
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);
}
示例3: BuildFromSecrets
import java.security.spec.RSAPrivateKeySpec; //导入依赖的package包/类
public static RsaSha256Fulfillment BuildFromSecrets(String PEMEncodedPrivateKey, byte[] message, SecureRandom saltRandom) {
ConditionType type = ConditionType.RSA_SHA256;
try {
// privKey = (RSAPrivateKeySpec)kf.generatePrivate(new PKCS8EncodedKeySpec(privateKey.payload));
RSAPrivateKeySpec privKeySpec = RsaSha256Fulfillment.parsePEMEncodedPrivateKey(PEMEncodedPrivateKey);
PrivateKey privKey = kf.generatePrivate(privKeySpec);
Signature signatureEngine = RsaSha256Fulfillment.getSignEngine();
signatureEngine.initSign(privKey /*, saltRandom */);
signatureEngine.update(message);
byte[] signature = signatureEngine.sign();
BigInteger modulus = privKeySpec.getModulus();
FulfillmentPayload payload = RsaSha256Fulfillment.calculatePayload(modulus, signature);
return new RsaSha256Fulfillment(type, payload, modulus, new SignaturePayload(signature));
} catch (Exception e) {
throw new RuntimeException(e.toString(), e);
}
}
示例4: loadRsaKeys
import java.security.spec.RSAPrivateKeySpec; //导入依赖的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);
}
示例5: decrypt
import java.security.spec.RSAPrivateKeySpec; //导入依赖的package包/类
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);
}
示例6: main
import java.security.spec.RSAPrivateKeySpec; //导入依赖的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));
}
示例7: init
import java.security.spec.RSAPrivateKeySpec; //导入依赖的package包/类
private static OpenSSLKey init(RSAPrivateKeySpec rsaKeySpec) throws InvalidKeySpecException {
final BigInteger modulus = rsaKeySpec.getModulus();
final BigInteger privateExponent = rsaKeySpec.getPrivateExponent();
if (modulus == null) {
throw new InvalidKeySpecException("modulus == null");
} else if (privateExponent == null) {
throw new InvalidKeySpecException("privateExponent == null");
}
try {
return new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA(
modulus.toByteArray(),
null,
privateExponent.toByteArray(),
null,
null,
null,
null,
null));
} catch (Exception e) {
throw new InvalidKeySpecException(e);
}
}
示例8: engineGeneratePrivate
import java.security.spec.RSAPrivateKeySpec; //导入依赖的package包/类
@Override
protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException {
if (keySpec == null) {
throw new InvalidKeySpecException("keySpec == null");
}
if (keySpec instanceof RSAPrivateCrtKeySpec) {
return new OpenSSLRSAPrivateCrtKey((RSAPrivateCrtKeySpec) keySpec);
} else if (keySpec instanceof RSAPrivateKeySpec) {
return new OpenSSLRSAPrivateKey((RSAPrivateKeySpec) keySpec);
} else if (keySpec instanceof PKCS8EncodedKeySpec) {
return OpenSSLKey.getPrivateKey((PKCS8EncodedKeySpec) keySpec,
NativeConstants.EVP_PKEY_RSA);
}
throw new InvalidKeySpecException("Must use RSAPublicKeySpec or PKCS8EncodedKeySpec; was "
+ keySpec.getClass().getName());
}
示例9: sshPrivateKey
import java.security.spec.RSAPrivateKeySpec; //导入依赖的package包/类
static PrivateKey sshPrivateKey(String key){
StringBuilder bob = new StringBuilder();
filter(list(key.split("\n")), (line) -> !(line.contains("-") || line.contains(":"))).forEach(
(line) -> {
bob.append(line);
bob.append("\n");
});
byte[] bytes = Base64.getDecoder().decode(bob.toString().replace("\n", ""));
DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes));
dieIf(rethrow(() -> in.read()) != 48, () -> "Unexpected Block Size in part 1");
dieIf(rethrow(() -> in.read()) != 130, () -> "Unexpected Block Size in part 2");
rethrow(() -> in.skipBytes(5));
BigInteger modulo = readBigInteger(in);
readBigInteger(in);
BigInteger exponent = readBigInteger(in);
RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulo, exponent);
return rethrow(() -> KeyFactory.getInstance("RSA").generatePrivate(rsaPrivateKeySpec));
}
示例10: sign
import java.security.spec.RSAPrivateKeySpec; //导入依赖的package包/类
public byte[] sign(byte[] b, int off, int len) throws CraiException {
try {
// HOLY FREAKING MOTHER OF A GOAT SCROAT WHY DOES JAVA MAKE THIS
// SO PAINFUL?!?!?!
Signature s = Signature.getInstance("SHA1withRSA");
KeyFactory keyFac = KeyFactory.getInstance("RSA");
PrivateKey key = keyFac.generatePrivate(new RSAPrivateKeySpec(
mN, mD));
s.initSign(key, ((JCERandom) mCraiRandom).mRandom);
s.update(b, off, len);
return s.sign();
} catch (Exception e) {
// JCE can throw weird exceptions at every stage :/
throw new CraiException("error performing RSA signature: " + e);
}
}
示例11: main
import java.security.spec.RSAPrivateKeySpec; //导入依赖的package包/类
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" );
}
示例12: main
import java.security.spec.RSAPrivateKeySpec; //导入依赖的package包/类
public static void main( final String[] args ) throws Exception {
final KeyFactory kf = KeyFactory.getInstance( "RSA" );
final BigInteger[] modExp = loadKey( "w:/privkey.rsa" );
final PrivateKey privKey = kf.generatePrivate( new RSAPrivateKeySpec( modExp[ 0 ], modExp[ 1 ] ) );
final Cipher cipher = Cipher.getInstance( "RSA" );
cipher.init( Cipher.ENCRYPT_MODE, privKey );
final byte[] encrypted = cipher.doFinal( DOCUMENT.getBytes( "UTF-8") );
System.out.println( "Successful encryption." );
try ( final FileOutputStream out = new FileOutputStream( "w:/encrypted.dat" ) ) {
out.write( encrypted );
}
}
示例13: loadPrivateKeyPEMPKCS1
import java.security.spec.RSAPrivateKeySpec; //导入依赖的package包/类
/**
* 加载 PKCS#1 编码的 pem 格式私钥
*
* @param privateKeyStr 私钥
* @throws Exception
*/
public void loadPrivateKeyPEMPKCS1(String privateKeyStr) throws Exception {
try {
byte[] e = Base64.decode(privateKeyStr);
// 读取 PKCS#1的私钥
RSAPrivateKeyStructure asn1PrivateKey = new RSAPrivateKeyStructure(
(ASN1Sequence) ASN1Sequence.fromByteArray(e));
RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(asn1PrivateKey.getModulus(),
asn1PrivateKey.getPrivateExponent());
// 实例化KeyFactory对象,并指定 RSA 算法
KeyFactory keyFactory = KeyFactory.getInstance(SIGN_ALGORITHMS);
// 获得 PrivateKey 对象
this.privateKey = keyFactory.generatePrivate(rsaPrivateKeySpec);
} catch (NoSuchAlgorithmException var6) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException var7) {
throw new Exception("私钥非法");
} catch (IOException var8) {
throw new Exception("私钥数据内容读取错误");
} catch (NullPointerException var9) {
throw new Exception("私钥数据为空");
}
}
示例14: parsePemPrivateKey
import java.security.spec.RSAPrivateKeySpec; //导入依赖的package包/类
public static RSAPrivateKeySpec parsePemPrivateKey(String pemPrivateKey)
throws InvalidKeyException {
pemPrivateKey = pemPrivateKey.replace("\n", "");
Matcher matcher = PRIVATE_KEY_PATTERN.matcher(pemPrivateKey);
if (!matcher.matches()) {
throw new InvalidKeyException();
}
String pemKey = matcher.group(1);
BaseEncoding encoding = BaseEncoding.base64();
byte[] derKey = encoding.decode(pemKey);
List<byte[]> fields;
try {
fields = parsePrivateKeyAsn1(ByteBuffer.wrap(derKey));
} catch (IllegalArgumentException e) {
throw new InvalidKeyException(e);
}
BigInteger mod = new BigInteger(fields.get(1));
BigInteger exp = new BigInteger(fields.get(3));
return new RSAPrivateKeySpec(mod, exp);
}
示例15: testRSAMultiPrimePrivateCrtKeySpec12
import java.security.spec.RSAPrivateKeySpec; //导入依赖的package包/类
/**
* Test #12 for
* <code>RSAMultiPrimePrivateCrtKeySpec(BigInteger modulus,
* BigInteger publicExponent,
* BigInteger privateExponent,
* BigInteger primeP,
* BigInteger primeQ,
* BigInteger primeExponentP,
* BigInteger primeExponentQ,
* BigInteger crtCoefficient,
* RSAOtherPrimeInfo[] otherPrimeInfo)
* </code> ctor<br>
* Assertion: constructs <code>RSAMultiPrimePrivateCrtKeySpec</code>
* object using valid parameters. Constructed object must be
* instance of RSAPrivateKeySpec.
*/
@TestTargetNew(
level = TestLevel.PARTIAL_COMPLETE,
notes = "Verifies constructor using valid parameters. Constructed object must be instance of RSAPrivateKeySpec.",
method = "RSAMultiPrimePrivateCrtKeySpec",
args = {java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.security.spec.RSAOtherPrimeInfo[].class}
)
public final void testRSAMultiPrimePrivateCrtKeySpec12() {
KeySpec ks = new RSAMultiPrimePrivateCrtKeySpec(
BigInteger.ONE,
BigInteger.ONE,
BigInteger.ONE,
BigInteger.ONE,
BigInteger.ONE,
BigInteger.ONE,
BigInteger.ONE,
BigInteger.ONE,
opi);
assertTrue(ks instanceof RSAPrivateKeySpec);
}