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