Java Examples for java.security.spec.PKCS8EncodedKeySpec
The following java examples will help you to understand the usage of java.security.spec.PKCS8EncodedKeySpec. These source code samples are taken from different open source projects.
Example 1
| Project: Android-Pay-master File: SignUtils.java View source code |
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 2
| Project: AndroidProjectStroe-master File: SignUtils.java View source code |
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance(ALGORITHM, "BC");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 3
| Project: basePay-master File: SignUtils.java View source code |
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 4
| Project: bc-java-master File: EncryptedPrivateKeyInfoTest.java View source code |
public void performTest() throws Exception {
doTestWithExplicitIV();
KeyPairGenerator fact = KeyPairGenerator.getInstance("RSA", "BC");
fact.initialize(512, new SecureRandom());
KeyPair keyPair = fact.generateKeyPair();
PrivateKey priKey = keyPair.getPrivate();
PublicKey pubKey = keyPair.getPublic();
//
// set up the parameters
//
byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int iterationCount = 100;
PBEParameterSpec defParams = new PBEParameterSpec(salt, iterationCount);
AlgorithmParameters params = AlgorithmParameters.getInstance(alg, "BC");
params.init(defParams);
//
// set up the key
//
char[] password1 = { 'h', 'e', 'l', 'l', 'o' };
PBEKeySpec pbeSpec = new PBEKeySpec(password1);
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg, "BC");
Cipher cipher = Cipher.getInstance(alg, "BC");
cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), params);
byte[] wrappedKey = cipher.wrap(priKey);
//
// create encrypted object
//
EncryptedPrivateKeyInfo pInfo = new EncryptedPrivateKeyInfo(params, wrappedKey);
//
// decryption step
//
char[] password2 = { 'h', 'e', 'l', 'l', 'o' };
pbeSpec = new PBEKeySpec(password2);
cipher = Cipher.getInstance(pInfo.getAlgName(), "BC");
cipher.init(Cipher.DECRYPT_MODE, keyFact.generateSecret(pbeSpec), pInfo.getAlgParameters());
PKCS8EncodedKeySpec keySpec = pInfo.getKeySpec(cipher);
if (!MessageDigest.isEqual(priKey.getEncoded(), keySpec.getEncoded())) {
fail("Private key does not match");
}
//
// using Cipher parameters test
//
pbeSpec = new PBEKeySpec(password1);
keyFact = SecretKeyFactory.getInstance(alg, "BC");
cipher = Cipher.getInstance(alg, "BC");
cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), params);
wrappedKey = cipher.wrap(priKey);
//
// create encrypted object
//
pInfo = new EncryptedPrivateKeyInfo(cipher.getParameters(), wrappedKey);
//
// decryption step
//
pbeSpec = new PBEKeySpec(password2);
cipher = Cipher.getInstance(pInfo.getAlgName(), "BC");
cipher.init(Cipher.DECRYPT_MODE, keyFact.generateSecret(pbeSpec), pInfo.getAlgParameters());
keySpec = pInfo.getKeySpec(cipher);
if (!MessageDigest.isEqual(priKey.getEncoded(), keySpec.getEncoded())) {
fail("Private key does not match");
}
}Example 5
| Project: CampusAssistant-master File: SignUtils.java View source code |
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 6
| Project: Dreamiya-master File: SignUtils.java View source code |
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
System.out.println(">>>###>>>> Exception");
e.printStackTrace();
return null;
}
}Example 7
| Project: FanXin2.0_IM-master File: SignUtils.java View source code |
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 8
| Project: GoldAssistant-master File: SignUtils.java View source code |
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
// KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
KeyFactory keyf = KeyFactory.getInstance("RSA", "BC");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 9
| Project: GoldAssistant2-master File: SignUtils.java View source code |
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
// KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
KeyFactory keyf = KeyFactory.getInstance("RSA", "BC");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 10
| Project: irma_future_id-master File: NamedCurveTest.java View source code |
public TestResult perform() {
try {
ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(name);
if (ecSpec == null) {
return new SimpleTestResult(false, getName() + " no curve for " + name + " found.");
}
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDH", "BC");
g.initialize(ecSpec, new SecureRandom());
//
// a side
//
KeyPair aKeyPair = g.generateKeyPair();
KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDHC", "BC");
aKeyAgree.init(aKeyPair.getPrivate());
//
// b side
//
KeyPair bKeyPair = g.generateKeyPair();
KeyAgreement bKeyAgree = KeyAgreement.getInstance("ECDHC", "BC");
bKeyAgree.init(bKeyPair.getPrivate());
//
// agreement
//
aKeyAgree.doPhase(bKeyPair.getPublic(), true);
bKeyAgree.doPhase(aKeyPair.getPublic(), true);
BigInteger k1 = new BigInteger(aKeyAgree.generateSecret());
BigInteger k2 = new BigInteger(bKeyAgree.generateSecret());
if (!k1.equals(k2)) {
return new SimpleTestResult(false, getName() + " 2-way test failed");
}
//
// public key encoding test
//
byte[] pubEnc = aKeyPair.getPublic().getEncoded();
KeyFactory keyFac = KeyFactory.getInstance("ECDH", "BC");
X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc);
ECPublicKey pubKey = (ECPublicKey) keyFac.generatePublic(pubX509);
if (!pubKey.getQ().equals(((ECPublicKey) aKeyPair.getPublic()).getQ())) {
return new SimpleTestResult(false, getName() + ": public key encoding (Q test) failed");
}
if (!(pubKey.getParameters() instanceof ECNamedCurveParameterSpec)) {
return new SimpleTestResult(false, getName() + ": public key encoding not named curve");
}
//
// private key encoding test
//
byte[] privEnc = aKeyPair.getPrivate().getEncoded();
PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
ECPrivateKey privKey = (ECPrivateKey) keyFac.generatePrivate(privPKCS8);
if (!privKey.getD().equals(((ECPrivateKey) aKeyPair.getPrivate()).getD())) {
return new SimpleTestResult(false, getName() + ": private key encoding (D test) failed");
}
if (!(privKey.getParameters() instanceof ECNamedCurveParameterSpec)) {
return new SimpleTestResult(false, getName() + ": private key encoding not named curve");
}
if (!((ECNamedCurveParameterSpec) privKey.getParameters()).getName().equals(name)) {
return new SimpleTestResult(false, getName() + ": private key encoding wrong named curve");
}
return new SimpleTestResult(true, getName() + ": Okay");
} catch (Exception e) {
return new SimpleTestResult(false, getName() + ": exception - " + e.toString());
}
}Example 11
| Project: jframe-master File: RSA.java View source code |
/**
* RSAç¾å??
* @param content å¾…ç¾å??æ•°æ?®
* @param privateKey 商户�钥
* @param input_charset ç¼–ç ?æ ¼å¼?
* @return ç¾å??值
*/
public static String sign(String content, String privateKey, String input_charset) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(input_charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 12
| Project: Meishuquan-master File: SignUtils.java View source code |
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 13
| Project: mfh-app-framework-master File: SignUtils.java View source code |
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
// KeyFactory keyf = KeyFactory.getInstance(ALGORITHM, "BC");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 14
| Project: MUtils-master File: SignUtils.java View source code |
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 15
| Project: prim-ftpd-master File: KeyGenerator.java View source code |
public void generate(FileOutputStream pubKeyFos, FileOutputStream privKeyFos) throws IOException, NoSuchAlgorithmException {
SecureRandom sr = new SecureRandom();
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_ALGO);
keyGen.initialize(KEY_SIZE, sr);
KeyPair keypair = keyGen.generateKeyPair();
PrivateKey privKey = keypair.getPrivate();
PublicKey pubKey = keypair.getPublic();
pubKeyFos.write(pubKey.getEncoded());
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privKey.getEncoded());
privKeyFos.write(privKeySpec.getEncoded());
}Example 16
| Project: shopping-master File: SignUtils.java View source code |
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 17
| Project: keycloak-master File: DerUtils.java View source code |
public static PrivateKey decodePrivateKey(InputStream is) throws Exception {
DataInputStream dis = new DataInputStream(is);
byte[] keyBytes = new byte[dis.available()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
return kf.generatePrivate(spec);
}Example 18
| Project: an2linuxclient-master File: RsaHelper.java View source code |
static PrivateKey getPrivateKey(Context c) {
try {
SharedPreferences deviceKeyPref = c.getSharedPreferences(c.getString(R.string.device_key_and_cert), MODE_PRIVATE);
byte[] privateKeyBytes = Base64.decode(deviceKeyPref.getString(c.getString(R.string.privatekey), ""), Base64.DEFAULT);
return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
} catch (Exception e) {
Log.e("RsaHelper", "getPrivateKey");
Log.e("StackTrace", Log.getStackTraceString(e));
return null;
}
}Example 19
| Project: bugvm-master File: OpenSSLKey.java View source code |
static PrivateKey getPrivateKey(PKCS8EncodedKeySpec keySpec, int type) throws InvalidKeySpecException { PKCS8EncodedKeySpec pkcs8KeySpec = (PKCS8EncodedKeySpec) keySpec; final OpenSSLKey key; try { key = new OpenSSLKey(NativeCrypto.d2i_PKCS8_PRIV_KEY_INFO(pkcs8KeySpec.getEncoded())); } catch (Exception e) { throw new InvalidKeySpecException(e); } if (NativeCrypto.EVP_PKEY_type(key.getPkeyContext()) != type) { throw new InvalidKeySpecException("Unexpected key type"); } try { return key.getPrivateKey(); } catch (NoSuchAlgorithmException e) { throw new InvalidKeySpecException(e); } }
Example 20
| Project: cas-server-4.0.1-master File: PrivateKeyFactoryBean.java View source code |
protected Object createInstance() throws Exception {
final InputStream privKey = this.location.getInputStream();
try {
final byte[] bytes = new byte[privKey.available()];
privKey.read(bytes);
privKey.close();
final PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance(this.algorithm);
return factory.generatePrivate(privSpec);
} finally {
privKey.close();
}
}Example 21
| Project: core-ng-project-master File: Signature.java View source code |
public Signature privateKey(byte[] privateKeyValue) {
try {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyValue);
KeyFactory keyFactory = KeyFactory.getInstance(RSA.ALGORITHM_RSA);
privateKey = keyFactory.generatePrivate(keySpec);
return this;
} catch (NoSuchAlgorithmExceptionInvalidKeySpecException | e) {
throw new Error(e);
}
}Example 22
| Project: dex2jar-master File: ApkSign.java View source code |
@Override
protected void doCommandLine() throws Exception {
if (remainingArgs.length != 1) {
usage();
return;
}
Path apkIn = new File(remainingArgs[0]).toPath();
if (!Files.exists(apkIn)) {
System.err.println(apkIn + " is not exists");
usage();
return;
}
if (output == null) {
if (Files.isDirectory(apkIn)) {
output = new File(apkIn.getFileName() + "-signed.apk").toPath();
} else {
output = new File(getBaseName(apkIn.getFileName().toString()) + "-signed.apk").toPath();
}
}
if (Files.exists(output) && !forceOverwrite) {
System.err.println(output + " exists, use --force to overwrite");
usage();
return;
}
Path tmp = null;
try {
final Path realJar;
if (Files.isDirectory(apkIn)) {
realJar = Files.createTempFile("d2j", ".jar");
tmp = realJar;
System.out.println("zipping " + apkIn + " -> " + realJar);
try (FileSystem fs = createZip(realJar)) {
final Path outRoot = fs.getPath("/");
walkJarOrDir(apkIn, new FileVisitorX() {
@Override
public void visitFile(Path file, Path relative) throws IOException {
Files.copy(file, outRoot);
}
});
}
} else {
realJar = apkIn;
}
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(ApkSign.class.getResourceAsStream("ApkSign.cer"));
KeyFactory rSAKeyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = rSAKeyFactory.generatePrivate(new PKCS8EncodedKeySpec(ZipUtil.toByteArray(ApkSign.class.getResourceAsStream("ApkSign.private"))));
AbstractJarSign signer;
try {
signer = new SunJarSignImpl(cert, privateKey);
} catch (Exception cnfe) {
signer = new TinySignImpl();
}
signer.sign(apkIn.toFile(), output.toFile());
System.out.println("sign " + realJar + " -> " + output);
} finally {
if (tmp != null) {
Files.deleteIfExists(tmp);
}
}
}Example 23
| Project: i2p.i2p-master File: KeyFactory.java View source code |
/**
* Supports PKCS8EncodedKeySpec
*/
protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException {
if (keySpec instanceof ElGamalPrivateKeySpec) {
return new ElGamalPrivateKeyImpl((ElGamalPrivateKeySpec) keySpec);
}
if (keySpec instanceof PKCS8EncodedKeySpec) {
return new ElGamalPrivateKeyImpl((PKCS8EncodedKeySpec) keySpec);
}
throw new InvalidKeySpecException("key spec not recognised");
}Example 24
| Project: java_security-master File: RSATest.java View source code |
// jdk实现:
public static void jdkRSA() {
try {
// 1.�始化��方密钥
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(512);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
System.out.println("Public Key:" + Base64.encodeBase64String(rsaPublicKey.getEncoded()));
System.out.println("Private Key:" + Base64.encodeBase64String(rsaPrivateKey.getEncoded()));
// 2.ç§?é’¥åŠ å¯†ã€?公钥解密 ---- åŠ å¯†
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(src.getBytes());
System.out.println("ç§?é’¥åŠ å¯†ã€?公钥解密 ---- åŠ å¯†:" + Base64.encodeBase64String(result));
// 3.ç§?é’¥åŠ å¯†ã€?公钥解密 ---- 解密
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
result = cipher.doFinal(result);
System.out.println("ç§?é’¥åŠ å¯†ã€?公钥解密 ---- 解密:" + new String(result));
// 4.å…¬é’¥åŠ å¯†ã€?ç§?钥解密 ---- åŠ å¯†
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
KeyFactory keyFactory2 = KeyFactory.getInstance("RSA");
PublicKey publicKey2 = keyFactory2.generatePublic(x509EncodedKeySpec2);
Cipher cipher2 = Cipher.getInstance("RSA");
cipher2.init(Cipher.ENCRYPT_MODE, publicKey2);
byte[] result2 = cipher2.doFinal(src.getBytes());
System.out.println("å…¬é’¥åŠ å¯†ã€?ç§?钥解密 ---- åŠ å¯†:" + Base64.encodeBase64String(result2));
// 5.ç§?钥解密ã€?å…¬é’¥åŠ å¯† ---- 解密
PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
KeyFactory keyFactory5 = KeyFactory.getInstance("RSA");
PrivateKey privateKey5 = keyFactory5.generatePrivate(pkcs8EncodedKeySpec5);
Cipher cipher5 = Cipher.getInstance("RSA");
cipher5.init(Cipher.DECRYPT_MODE, privateKey5);
byte[] result5 = cipher5.doFinal(result2);
System.out.println("å…¬é’¥åŠ å¯†ã€?ç§?钥解密 ---- 解密:" + new String(result5));
} catch (Exception e) {
e.printStackTrace();
}
}Example 25
| Project: ldaptive-master File: PrivateKeyCredentialReader.java View source code |
/**
* Reads a private key from an input stream.
*
* @param is Input stream from which to read private key.
* @param params A single optional parameter, algorithm, may be specified. The default is RSA.
*
* @return Private key read from data in stream.
*
* @throws IOException On IO errors.
* @throws GeneralSecurityException On errors with the credential data.
*/
@Override
public PrivateKey read(final InputStream is, final String... params) throws IOException, GeneralSecurityException {
String algorithm = "RSA";
if (params.length > 0 && params[0] != null) {
algorithm = params[0];
}
final KeyFactory kf = KeyFactory.getInstance(algorithm);
final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(LdapUtils.readInputStream(getBufferedInputStream(is)));
return kf.generatePrivate(spec);
}Example 26
| Project: Mujina-master File: KeyStoreLocator.java View source code |
//privateKey must be in the DER unencrypted PKCS#8 format. See README.md
public static void addPrivateKey(KeyStore keyStore, String alias, String privateKey, String certificate, String password) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException, CertificateException {
String wrappedCert = wrapCert(certificate);
byte[] decodedKey = Base64.getDecoder().decode(privateKey.getBytes());
char[] passwordChars = password.toCharArray();
Certificate cert = certificateFactory.generateCertificate(new ByteArrayInputStream(wrappedCert.getBytes()));
ArrayList<Certificate> certs = new ArrayList<>();
certs.add(cert);
byte[] privKeyBytes = IOUtils.toByteArray(new ByteArrayInputStream(decodedKey));
KeySpec ks = new PKCS8EncodedKeySpec(privKeyBytes);
RSAPrivateKey privKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(ks);
keyStore.setKeyEntry(alias, privKey, passwordChars, certs.toArray(new Certificate[certs.size()]));
}Example 27
| Project: oobd-master File: KeyFactorySpi.java View source code |
protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException {
if (keySpec instanceof PKCS8EncodedKeySpec) {
try {
return generatePrivate(PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec) keySpec).getEncoded()));
} catch (Exception e) {
try {
return new BCRSAPrivateCrtKey(RSAPrivateKey.getInstance(((PKCS8EncodedKeySpec) keySpec).getEncoded()));
} catch (Exception ex) {
throw new ExtendedInvalidKeySpecException("unable to process key spec: " + e.toString(), e);
}
}
} else if (keySpec instanceof RSAPrivateCrtKeySpec) {
return new BCRSAPrivateCrtKey((RSAPrivateCrtKeySpec) keySpec);
} else if (keySpec instanceof RSAPrivateKeySpec) {
return new BCRSAPrivateKey((RSAPrivateKeySpec) keySpec);
}
throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}Example 28
| Project: pay-master File: RSA.java View source code |
/**
* RSAç¾å??
* @param content å¾…ç¾å??æ•°æ?®
* @param privateKey 商户�钥
* @param input_charset ç¼–ç ?æ ¼å¼?
* @return ç¾å??值
*/
public static String sign(String content, String privateKey, String input_charset) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(input_charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 29
| Project: Pitbull-master File: DerUtils.java View source code |
public static PrivateKey decodePrivateKey(InputStream is) throws Exception {
DataInputStream dis = new DataInputStream(is);
byte[] keyBytes = new byte[dis.available()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
return kf.generatePrivate(spec);
}Example 30
| Project: Resteasy-master File: ExampleSignTest.java View source code |
public static PrivateKey getPrivate(InputStream is) throws Exception {
DataInputStream dis = new DataInputStream(is);
byte[] keyBytes = new byte[dis.available()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}Example 31
| Project: RipplePower-master File: KeyFactorySpi.java View source code |
protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException {
if (keySpec instanceof PKCS8EncodedKeySpec) {
try {
return generatePrivate(PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec) keySpec).getEncoded()));
} catch (Exception e) {
try {
return new BCRSAPrivateCrtKey(RSAPrivateKey.getInstance(((PKCS8EncodedKeySpec) keySpec).getEncoded()));
} catch (Exception ex) {
throw new ExtendedInvalidKeySpecException("unable to process key spec: " + e.toString(), e);
}
}
} else if (keySpec instanceof RSAPrivateCrtKeySpec) {
return new BCRSAPrivateCrtKey((RSAPrivateCrtKeySpec) keySpec);
} else if (keySpec instanceof RSAPrivateKeySpec) {
return new BCRSAPrivateKey((RSAPrivateKeySpec) keySpec);
}
throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}Example 32
| Project: robovm-master File: EncodedKeySpec2Test.java View source code |
/**
* java.security.spec.EncodedKeySpec#getEncoded()
*/
public void test_getEncoded() throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
keyGen.initialize(1024);
KeyPair keys = keyGen.generateKeyPair();
KeyFactory fact = KeyFactory.getInstance("DSA");
// check public key encoding
byte[] encoded = keys.getPublic().getEncoded();
Key key = fact.generatePublic(new X509EncodedKeySpec(encoded));
assertTrue("public key encodings were different", isEqual(key, keys.getPublic()));
// check private key encoding
encoded = keys.getPrivate().getEncoded();
key = fact.generatePrivate(new PKCS8EncodedKeySpec(encoded));
assertTrue("private key encodings were different", isEqual(key, keys.getPrivate()));
}Example 33
| Project: saml-generator-master File: CertManager.java View source code |
/**
* gets credential used to sign saml assertionts that are produced. This method
* assumes the cert and pkcs formatted primary key are on file system. this data
* could be stored elsewhere e.g keystore
*
* a credential is used to sign saml response, and includes the private key
* as well as a cert for the public key
*
* @return
* @throws Throwable
*/
public Credential getSigningCredential(String publicKeyLocation, String privateKeyLocation) throws Throwable {
// create public key (cert) portion of credential
InputStream inStream = new FileInputStream(publicKeyLocation);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate publicKey = (X509Certificate) cf.generateCertificate(inStream);
inStream.close();
// create private key
RandomAccessFile raf = new RandomAccessFile(privateKeyLocation, "r");
byte[] buf = new byte[(int) raf.length()];
raf.readFully(buf);
raf.close();
PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(buf);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privateKey = kf.generatePrivate(kspec);
// create credential and initialize
BasicX509Credential credential = new BasicX509Credential();
credential.setEntityCertificate(publicKey);
credential.setPrivateKey(privateKey);
return credential;
}Example 34
| Project: JDK-master File: KeyRep.java View source code |
/**
* Resolve the Key object.
*
* <p> This method supports three Type/format combinations:
* <ul>
* <li> Type.SECRET/"RAW" - returns a SecretKeySpec object
* constructed using encoded key bytes and algorithm
* <li> Type.PUBLIC/"X.509" - gets a KeyFactory instance for
* the key algorithm, constructs an X509EncodedKeySpec with the
* encoded key bytes, and generates a public key from the spec
* <li> Type.PRIVATE/"PKCS#8" - gets a KeyFactory instance for
* the key algorithm, constructs a PKCS8EncodedKeySpec with the
* encoded key bytes, and generates a private key from the spec
* </ul>
*
* <p>
*
* @return the resolved Key object
*
* @exception ObjectStreamException if the Type/format
* combination is unrecognized, if the algorithm, key format, or
* encoded key bytes are unrecognized/invalid, of if the
* resolution of the key fails for any reason
*/
protected Object readResolve() throws ObjectStreamException {
try {
if (type == Type.SECRET && RAW.equals(format)) {
return new SecretKeySpec(encoded, algorithm);
} else if (type == Type.PUBLIC && X509.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePublic(new X509EncodedKeySpec(encoded));
} else if (type == Type.PRIVATE && PKCS8.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePrivate(new PKCS8EncodedKeySpec(encoded));
} else {
throw new NotSerializableException("unrecognized type/format combination: " + type + "/" + format);
}
} catch (NotSerializableException nse) {
throw nse;
} catch (Exception e) {
NotSerializableException nse = new NotSerializableException("java.security.Key: " + "[" + type + "] " + "[" + algorithm + "] " + "[" + format + "]");
nse.initCause(e);
throw nse;
}
}Example 35
| Project: cas-master File: PrivateKeyFactoryBean.java View source code |
private PrivateKey readDERPrivateKey() throws Exception {
LOGGER.debug("Attempting to read [{}] as DER", this.location.getFile());
try (InputStream privKey = this.location.getInputStream()) {
final byte[] bytes = new byte[privKey.available()];
privKey.read(bytes);
final PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(bytes);
final KeyFactory factory = KeyFactory.getInstance(this.algorithm);
return factory.generatePrivate(privSpec);
}
}Example 36
| Project: CASBaH-master File: KeyHelper.java View source code |
public static PrivateKey readKey(String keypass, byte[] keyData) throws CAProviderException {
try {
EncryptedPrivateKeyInfo pkInfo = new EncryptedPrivateKeyInfo(keyData);
PBEKeySpec keySpec = new PBEKeySpec(keypass.toCharArray());
SecretKeyFactory pbeKeyFactory = SecretKeyFactory.getInstance(pkInfo.getAlgName());
PKCS8EncodedKeySpec encodedKeySpec = pkInfo.getKeySpec(pbeKeyFactory.generateSecret(keySpec));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateCrtKey) keyFactory.generatePrivate(encodedKeySpec);
} catch (Exception e) {
throw new CAProviderException("Could not decode private key", e);
}
}Example 37
| Project: com.mzeat-master File: Rsa.java View source code |
public static String sign(String content, String privateKey) {
String charset = "utf-8";
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 38
| Project: cryptacular-master File: WrappedKeyTest.java View source code |
private static KeyPair readJCEKeyPair(final String algorithm, final String pubKeyPath, final String privKeyPath) throws Exception {
final PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(StreamUtil.readAll(privKeyPath));
final X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(StreamUtil.readAll(pubKeyPath));
final KeyFactory factory = KeyFactory.getInstance(algorithm);
return new KeyPair(factory.generatePublic(pubSpec), factory.generatePrivate(privSpec));
}Example 39
| Project: cryptoapplet-master File: ImportPrivateKey.java View source code |
/**
* @param args
*/
public static void main(String[] args) {
if (args.length != 4) {
System.out.println("Usage: KStool <keystore> " + "<key alias> <keystore password> <key file>");
System.exit(-1);
}
String ksFile = args[0];
String keyAlias = args[1];
char[] ksPass = args[2].toCharArray();
String keyFile = args[3];
try {
// read keystore file
FileInputStream fis = new FileInputStream(ksFile);
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(fis, ksPass);
// extract the Certificate Chain from the keystore
java.security.cert.Certificate[] certChain = new java.security.cert.Certificate[1];
certChain[0] = ks.getCertificate(keyAlias);
// read in the key file
FileInputStream fis2 = new FileInputStream(keyFile);
int b = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((b = fis2.read()) != -1) {
baos.write(b);
}
baos.flush();
byte[] keyBytes = baos.toByteArray();
// create PKCS8 key spec using key file
PKCS8EncodedKeySpec eks = new PKCS8EncodedKeySpec(keyBytes);
// use PKCS8 keyspec to generate a privatekey
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey pk = kf.generatePrivate(eks);
// add the key to the keystore and save keystore
ks.setKeyEntry(keyAlias, pk, ksPass, certChain);
ks.store(new FileOutputStream(ksFile), ksPass);
System.out.println("Successfully added Private Key to KeyStore!");
} catch (InvalidKeySpecException e) {
System.out.println("InvalidKeySpecException: " + e.getMessage());
System.out.println("\nThe PrivateKey you attempted\nto load from \"" + keyFile + "\"\nis not in PKCS8 format.");
} catch (Exception e) {
System.out.println("ERROR: " + e.getMessage());
}
}Example 40
| Project: ECMobile_Android-master File: Rsa.java View source code |
public static String sign(String content, String privateKey) {
String charset = "utf-8";
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA", "BC");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 41
| Project: factura-electronica-master File: PrivateKeyLoader.java View source code |
/**
*
* @param privateKeyInputStream private key's input stream
* @param keyPassword private key password
*
* @throws KeyException thrown when any security exception occurs
*/
public void setPrivateKey(InputStream privateKeyInputStream, String keyPassword) {
byte[] privateKeyByte = this.extractProtectedPrivateKey(privateKeyInputStream, keyPassword);
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyByte);
try {
this.key = KeyFactory.getInstance("RSA").generatePrivate(pkcs8EncodedKeySpec);
} catch (GeneralSecurityException gse) {
throw new KeyException("Error al obtener la información del certificado debido a su codificación", gse.getCause());
}
}Example 42
| Project: haox-master File: Pkix.java View source code |
public static PrivateKey getPrivateKey(InputStream inputStream, String password) throws GeneralSecurityException, IOException {
if (password == null)
password = "";
// If the provided InputStream is encrypted, we need a password to decrypt
// it. If the InputStream is not encrypted, then the password is ignored
// (can be null). The InputStream can be DER (raw ASN.1) or PEM (base64).
PKCS8Key pkcs8 = new PKCS8Key(inputStream, password.toCharArray());
// If an unencrypted PKCS8 key was provided, then this actually returns
// exactly what was originally passed inputStream (with no changes). If an OpenSSL
// key was provided, it gets reformatted as PKCS #8 first, and so these
// bytes will still be PKCS #8, not OpenSSL.
byte[] decrypted = pkcs8.getDecryptedBytes();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decrypted);
// A Java PrivateKey object is born.
PrivateKey pk = null;
if (pkcs8.isDSA()) {
pk = KeyFactory.getInstance("DSA").generatePrivate(spec);
} else if (pkcs8.isRSA()) {
pk = KeyFactory.getInstance("RSA").generatePrivate(spec);
}
// For lazier types:
pk = pkcs8.getPrivateKey();
return pk;
}Example 43
| Project: java-jwt-master File: PemUtils.java View source code |
private static PrivateKey getPrivateKey(byte[] keyBytes, String algorithm) {
PrivateKey privateKey = null;
try {
KeyFactory kf = KeyFactory.getInstance(algorithm);
EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
privateKey = kf.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
System.out.println("Could not reconstruct the private key, the given algorithm could not be found.");
} catch (InvalidKeySpecException e) {
System.out.println("Could not reconstruct the private key");
}
return privateKey;
}Example 44
| Project: jinhe-tss-master File: LicenseFactory.java View source code |
/**
* 用ç§?钥对license进行数æ?®ç¾å??
* @param license
* @throws Exception
*/
public static synchronized void sign(License license) throws Exception {
String privateKey = FileHelper.readFile(new File(PRIVATE_KEY_FILE));
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(EasyUtils.decodeHex(privateKey.trim()));
PrivateKey privKey = keyFactory.generatePrivate(privKeySpec);
Signature sig = Signature.getInstance("SHA1withDSA");
sig.initSign(privKey);
sig.update(license.getFingerprint());
license.licenseSignature = EasyUtils.encodeHex(sig.sign());
}Example 45
| Project: klarna-on-demand-android-master File: CryptoBaseTest.java View source code |
@Test
public void sign_shouldCaclculateAValidSignature() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, InvalidKeySpecException {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decode("MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAskcFcO+vuYAQfRjCGkhZXMGlrtpbJZRq9y0SJi2DlKo2Ph58Ni9j6mN4DVKdSSJhuR/myNzXmszLzZIgq1AwpQIDAQABAkA641rYw1O4YqUPrW3wYJWkHhMsftQ8xZnPrAOiuMYOBN5jJ1pKBXiy3nHxBCiSWAJY+kWSWzbY1zzecBtmbCDBAiEA1lrU0Uhk3H7v7qyZPWIgu2pHYi+/W17c3jsl/NgHQfMCIQDU6dea1HCfWcU31cW/wShhzXd4h1H6AqEmRIEGnCLRBwIhAINNAC9x+NZXqwC4GOXQxdwHLdKnDMAbS4+VC5/ldAyhAiEAs4/PhMWbgdisyi0gzFpz2x/0nRLK4SXskKB/jHqLpmsCICTcahC8Xm8EFD/kxkDpI2oMZuWa2ghvZ1zuSMpnfkgE", Base64.DEFAULT));
KeyFactory keyFact = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFact.generatePrivate(pkcs8EncodedKeySpec);
assertThat(CryptoBase.sign("my_data", privateKey)).isEqualTo("n8PEnZ5s5Cn39Jx2nMRf+cTbw7YIw5ak0HBEQJUl4mX/rMjo1SQe/56elt95c5H9TydbEcmvDeDt\n2SpHXylNDA==\n");
}Example 46
| Project: LanXchange-master File: Signer.java View source code |
/**
* Sign the file named lxc.zip and exit.
*
* @param args ignored
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// Sign file
KeyFactory fact = KeyFactory.getInstance("RSA");
FileInputStream ins = new FileInputStream(new File("lxc_updates.priv"));
byte[] b = new byte[ins.available()];
ins.read(b);
ins.close();
PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(b);
PrivateKey priKey = fact.generatePrivate(priKeySpec);
Signature sign = Signature.getInstance("SHA256withRSA");
sign.initSign(priKey);
FileInputStream in = new FileInputStream("lxc.zip");
int bufSize = 1024;
byte[] buffer = new byte[bufSize];
int n = in.read(buffer, 0, bufSize);
while (n != -1) {
sign.update(buffer, 0, n);
n = in.read(buffer, 0, bufSize);
}
in.close();
FileOutputStream out = new FileOutputStream("lxc.sign");
byte[] signb = sign.sign();
out.write(signb);
out.close();
}Example 47
| Project: oauth-master File: RSASha1SignatureServiceTest.java View source code |
/**
* Created primary key using openssl.
*
* openssl req -x509 -nodes -days 365 -newkey rsa:1024 -sha1 -subj '/C=GB/ST=/L=Manchester/CN=www.example.com'
* -keyout myrsakey.pem -out /tmp/myrsacert.pem openssl pkcs8 -in myrsakey.pem -topk8 -nocrypt -out myrsakey.pk8
*/
private static PrivateKey getPrivateKey() {
final String str = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMPQ5BCMxlUq2TYy\n" + "iRIoEUsz6HGTJhHuasS2nx1Se4Co3lxwxyubVdFj8AuhHNJSmJvjlpbTsGOjLZpr\n" + "HyDEDdJmf1Fensh1MhUnBZ4a7uLrZrKzFHHJdamX9pxapB89vLeHlCot9hVXdrZH\n" + "nNtg6FdmRKH/8gbs8iDyIayFvzYDAgMBAAECgYA+c9MpTBy9cQsR9BAvkEPjvkx2\n" + "XL4ZnfbDgpNA4Nuu7yzsQrPjPomiXMNkkiAFHH67yVxwAlgRjyuuQlgNNTpKvyQt\n" + "XcHxffnU0820VmE23M+L7jg2TlB3+rUnEDmDvCoyjlwGDR6lNb7t7Fgg2iR+iaov\n" + "0iVzz+l9w0slRlyGsQJBAPWXW2m3NmFgqfDxtw8fsKC2y8o17/cnPjozRGtWb8LQ\n" + "g3VCb8kbOFHOYNGazq3M7+wD1qILF2h/HecgK9eQrZ0CQQDMHXoJMfKKbrFrTKgE\n" + "zyggO1gtuT5OXYeFewMEb5AbDI2FfSc2YP7SHij8iQ2HdukBrbTmi6qxh3HmIR58\n" + "I/AfAkEA0Y9vr0tombsUB8cZv0v5OYoBZvCTbMANtzfb4AOHpiKqqbohDOevLQ7/\n" + "SpvgVCmVaDz2PptcRAyEBZ5MCssneQJAB2pmvaDH7Ambfod5bztLfOhLCtY5EkXJ\n" + "n6rZcDbRaHorRhdG7m3VtDKOUKZ2DF7glkQGV33phKukErVPUzlHBwJAScD9TqaG\n" + "wJ3juUsVtujV23SnH43iMggXT7m82STpPGam1hPfmqu2Z0niePFo927ogQ7H1EMJ\n" + "UHgqXmuvk2X/Ww==";
try {
final KeyFactory fac = KeyFactory.getInstance("RSA");
final PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(str));
return fac.generatePrivate(privKeySpec);
} catch (NoSuchAlgorithmExceptionInvalidKeySpecException | e) {
throw new RuntimeException(e);
}
}Example 48
| Project: openiot-master File: KeyGeneration.java View source code |
public static void main(String[] args) throws Exception {
FileInputStream keyfis = new FileInputStream(args[0]);
byte[] encKey = new byte[keyfis.available()];
keyfis.read(encKey);
keyfis.close();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
keyfis = new FileInputStream(args[1]);
encKey = new byte[keyfis.available()];
keyfis.read(encKey);
keyfis.close();
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(encKey);
keyFactory = KeyFactory.getInstance("DSA", "SUN");
PrivateKey privKey = keyFactory.generatePrivate(privKeySpec);
// Signing start.
Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");
dsa.initSign(privKey);
dsa.update(new String("Select * from bla").getBytes());
byte[] signature = dsa.sign();
// System.out.println (new String (coded)) ;
// Verification start.
Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
sig.initVerify(pubKey);
sig.update("Select * from bla".getBytes());
boolean verifies = sig.verify(signature);
System.out.println("signature verifies: " + verifies);
}Example 49
| Project: redPandaj-master File: RSAKey.java View source code |
public static RSAKey newInstance(String encodedPublicKey, String encodedprivateKey) {
try {
PublicKey publicKey = null;
if (encodedPublicKey != null) {
byte[] publicKeyBytes = Base58.decode(encodedPublicKey);
publicKey = KeyFactory.getInstance(Algorithm).generatePublic(new X509EncodedKeySpec(publicKeyBytes));
}
PrivateKey privateKey = null;
if (encodedprivateKey != null) {
byte[] privateKeyBytes = Base58.decode(encodedprivateKey);
privateKey = KeyFactory.getInstance(Algorithm).generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
}
return new RSAKey(publicKey, privateKey);
} catch (AddressFormatException ex) {
Logger.getLogger(RSAKey.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAKey.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException ex) {
Logger.getLogger(RSAKey.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}Example 50
| Project: SamplePaymentProject-master File: KeyHandler.java View source code |
public static PrivateKey decodePrivateKey(String privateKeyEncoded, PKIAlgorithm algorithm) throws UnknownPKIAlgorithmException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
if (algorithm.getCode() != PKIAlgorithm.DEFAULT.getCode())
throw new UnknownPKIAlgorithmException();
byte[] decoded = Base64.decode(privateKeyEncoded.getBytes(), Base64.DEFAULT);
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(decoded);
KeyFactory keyFactory = KeyFactory.getInstance(algorithm.getKeyPairAlgorithm(), SECURITY_PROVIDER);
return keyFactory.generatePrivate(privateKeySpec);
}Example 51
| Project: scribe-master File: RSASha1SignatureServiceTest.java View source code |
/**
* Created primary key using openssl.
*
* openssl req -x509 -nodes -days 365 -newkey rsa:1024 -sha1 -subj '/C=GB/ST=/L=Manchester/CN=www.example.com'
* -keyout myrsakey.pem -out /tmp/myrsacert.pem openssl pkcs8 -in myrsakey.pem -topk8 -nocrypt -out myrsakey.pk8
*/
private static PrivateKey getPrivateKey() {
final String str = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMPQ5BCMxlUq2TYy\n" + "iRIoEUsz6HGTJhHuasS2nx1Se4Co3lxwxyubVdFj8AuhHNJSmJvjlpbTsGOjLZpr\n" + "HyDEDdJmf1Fensh1MhUnBZ4a7uLrZrKzFHHJdamX9pxapB89vLeHlCot9hVXdrZH\n" + "nNtg6FdmRKH/8gbs8iDyIayFvzYDAgMBAAECgYA+c9MpTBy9cQsR9BAvkEPjvkx2\n" + "XL4ZnfbDgpNA4Nuu7yzsQrPjPomiXMNkkiAFHH67yVxwAlgRjyuuQlgNNTpKvyQt\n" + "XcHxffnU0820VmE23M+L7jg2TlB3+rUnEDmDvCoyjlwGDR6lNb7t7Fgg2iR+iaov\n" + "0iVzz+l9w0slRlyGsQJBAPWXW2m3NmFgqfDxtw8fsKC2y8o17/cnPjozRGtWb8LQ\n" + "g3VCb8kbOFHOYNGazq3M7+wD1qILF2h/HecgK9eQrZ0CQQDMHXoJMfKKbrFrTKgE\n" + "zyggO1gtuT5OXYeFewMEb5AbDI2FfSc2YP7SHij8iQ2HdukBrbTmi6qxh3HmIR58\n" + "I/AfAkEA0Y9vr0tombsUB8cZv0v5OYoBZvCTbMANtzfb4AOHpiKqqbohDOevLQ7/\n" + "SpvgVCmVaDz2PptcRAyEBZ5MCssneQJAB2pmvaDH7Ambfod5bztLfOhLCtY5EkXJ\n" + "n6rZcDbRaHorRhdG7m3VtDKOUKZ2DF7glkQGV33phKukErVPUzlHBwJAScD9TqaG\n" + "wJ3juUsVtujV23SnH43iMggXT7m82STpPGam1hPfmqu2Z0niePFo927ogQ7H1EMJ\n" + "UHgqXmuvk2X/Ww==";
try {
final KeyFactory fac = KeyFactory.getInstance("RSA");
final PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(str));
return fac.generatePrivate(privKeySpec);
} catch (NoSuchAlgorithmExceptionInvalidKeySpecException | e) {
throw new RuntimeException(e);
}
}Example 52
| Project: scribejava-master File: RSASha1SignatureServiceTest.java View source code |
/**
* Created primary key using openssl.
*
* openssl req -x509 -nodes -days 365 -newkey rsa:1024 -sha1 -subj '/C=GB/ST=/L=Manchester/CN=www.example.com'
* -keyout myrsakey.pem -out /tmp/myrsacert.pem openssl pkcs8 -in myrsakey.pem -topk8 -nocrypt -out myrsakey.pk8
*/
private static PrivateKey getPrivateKey() {
final String str = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMPQ5BCMxlUq2TYy\n" + "iRIoEUsz6HGTJhHuasS2nx1Se4Co3lxwxyubVdFj8AuhHNJSmJvjlpbTsGOjLZpr\n" + "HyDEDdJmf1Fensh1MhUnBZ4a7uLrZrKzFHHJdamX9pxapB89vLeHlCot9hVXdrZH\n" + "nNtg6FdmRKH/8gbs8iDyIayFvzYDAgMBAAECgYA+c9MpTBy9cQsR9BAvkEPjvkx2\n" + "XL4ZnfbDgpNA4Nuu7yzsQrPjPomiXMNkkiAFHH67yVxwAlgRjyuuQlgNNTpKvyQt\n" + "XcHxffnU0820VmE23M+L7jg2TlB3+rUnEDmDvCoyjlwGDR6lNb7t7Fgg2iR+iaov\n" + "0iVzz+l9w0slRlyGsQJBAPWXW2m3NmFgqfDxtw8fsKC2y8o17/cnPjozRGtWb8LQ\n" + "g3VCb8kbOFHOYNGazq3M7+wD1qILF2h/HecgK9eQrZ0CQQDMHXoJMfKKbrFrTKgE\n" + "zyggO1gtuT5OXYeFewMEb5AbDI2FfSc2YP7SHij8iQ2HdukBrbTmi6qxh3HmIR58\n" + "I/AfAkEA0Y9vr0tombsUB8cZv0v5OYoBZvCTbMANtzfb4AOHpiKqqbohDOevLQ7/\n" + "SpvgVCmVaDz2PptcRAyEBZ5MCssneQJAB2pmvaDH7Ambfod5bztLfOhLCtY5EkXJ\n" + "n6rZcDbRaHorRhdG7m3VtDKOUKZ2DF7glkQGV33phKukErVPUzlHBwJAScD9TqaG\n" + "wJ3juUsVtujV23SnH43iMggXT7m82STpPGam1hPfmqu2Z0niePFo927ogQ7H1EMJ\n" + "UHgqXmuvk2X/Ww==";
try {
final KeyFactory fac = KeyFactory.getInstance("RSA");
final PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(str));
return fac.generatePrivate(privKeySpec);
} catch (NoSuchAlgorithmExceptionInvalidKeySpecException | e) {
throw new RuntimeException(e);
}
}Example 53
| Project: world-master File: Rsa.java View source code |
public static String sign(String content, String privateKey) {
String charset = "utf-8";
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 54
| Project: agorava-core-master File: RSASha1SignatureServiceTest.java View source code |
/**
* Created primary key using openssl.
* <p/>
* openssl req -x509 -nodes -days 365 -newkey rsa:1024 -sha1 -subj '/C=GB/ST=/L=Manchester/CN=www.example.com' -keyout
* myrsakey.pem -out /tmp/myrsacert.pem
* openssl pkcs8 -in myrsakey.pem -topk8 -nocrypt -out myrsakey.pk8
*/
private static PrivateKey getPrivateKey() {
String str = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMPQ5BCMxlUq2TYy\n" + "iRIoEUsz6HGTJhHuasS2nx1Se4Co3lxwxyubVdFj8AuhHNJSmJvjlpbTsGOjLZpr\n" + "HyDEDdJmf1Fensh1MhUnBZ4a7uLrZrKzFHHJdamX9pxapB89vLeHlCot9hVXdrZH\n" + "nNtg6FdmRKH/8gbs8iDyIayFvzYDAgMBAAECgYA+c9MpTBy9cQsR9BAvkEPjvkx2\n" + "XL4ZnfbDgpNA4Nuu7yzsQrPjPomiXMNkkiAFHH67yVxwAlgRjyuuQlgNNTpKvyQt\n" + "XcHxffnU0820VmE23M+L7jg2TlB3+rUnEDmDvCoyjlwGDR6lNb7t7Fgg2iR+iaov\n" + "0iVzz+l9w0slRlyGsQJBAPWXW2m3NmFgqfDxtw8fsKC2y8o17/cnPjozRGtWb8LQ\n" + "g3VCb8kbOFHOYNGazq3M7+wD1qILF2h/HecgK9eQrZ0CQQDMHXoJMfKKbrFrTKgE\n" + "zyggO1gtuT5OXYeFewMEb5AbDI2FfSc2YP7SHij8iQ2HdukBrbTmi6qxh3HmIR58\n" + "I/AfAkEA0Y9vr0tombsUB8cZv0v5OYoBZvCTbMANtzfb4AOHpiKqqbohDOevLQ7/\n" + "SpvgVCmVaDz2PptcRAyEBZ5MCssneQJAB2pmvaDH7Ambfod5bztLfOhLCtY5EkXJ\n" + "n6rZcDbRaHorRhdG7m3VtDKOUKZ2DF7glkQGV33phKukErVPUzlHBwJAScD9TqaG\n" + "wJ3juUsVtujV23SnH43iMggXT7m82STpPGam1hPfmqu2Z0niePFo927ogQ7H1EMJ\n" + "UHgqXmuvk2X/Ww==";
try {
KeyFactory fac = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(str));
return fac.generatePrivate(privKeySpec);
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 55
| Project: android-libcore64-master File: PKCS8EncodedKeySpecTest.java View source code |
//
// Tests
//
/**
* Test for <code>PKCS8EncodedKeySpec</code> constructor<br>
* Assertion: constructs new <code>PKCS8EncodedKeySpec</code>
* object using valid parameter
*/
public final void testPKCS8EncodedKeySpec() {
byte[] encodedKey = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };
EncodedKeySpec eks = new PKCS8EncodedKeySpec(encodedKey);
assertTrue(eks instanceof PKCS8EncodedKeySpec);
try {
eks = new PKCS8EncodedKeySpec(null);
fail("expected NullPointerException");
} catch (NullPointerException e) {
}
}Example 56
| Project: android_chat-master File: Encryption.java View source code |
public String decrypt(String privateKey, String msg) {
try {
PrivateKey privKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(th.base64Decode(privateKey)));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] cipherData = cipher.doFinal(th.base64Decode(msg));
return new String(cipherData);
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, e.getMessage());
} catch (NoSuchPaddingException e) {
Log.e(TAG, e.getMessage());
} catch (InvalidKeyException e) {
Log.e(TAG, e.getMessage());
} catch (IllegalBlockSizeException e) {
Log.e(TAG, e.getMessage());
} catch (BadPaddingException e) {
Log.e(TAG, e.getMessage());
} catch (InvalidKeySpecException e) {
Log.e(TAG, e.getMessage());
}
return null;
}Example 57
| Project: android_external_GmsLib-master File: InstanceIdStore.java View source code |
public KeyPair getKeyPair(String subtype) {
String pub = get(subtype, "|P|");
String priv = get(subtype, "|K|");
if (pub == null || priv == null) {
return null;
}
try {
byte[] pubKey = Base64.decode(pub, Base64.URL_SAFE);
byte[] privKey = Base64.decode(priv, Base64.URL_SAFE);
KeyFactory rsaFactory = KeyFactory.getInstance("RSA");
return new KeyPair(rsaFactory.generatePublic(new X509EncodedKeySpec(pubKey)), rsaFactory.generatePrivate(new PKCS8EncodedKeySpec(privKey)));
} catch (Exception e) {
Log.w(TAG, "Invalid key stored " + e);
return null;
}
}Example 58
| Project: android_libcore-master File: PKCS8EncodedKeySpecTest.java View source code |
//
// Tests
//
/**
* Test for <code>PKCS8EncodedKeySpec</code> constructor<br>
* Assertion: constructs new <code>PKCS8EncodedKeySpec</code>
* object using valid parameter
*/
@TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "PKCS8EncodedKeySpec", args = { byte[].class })
public final void testPKCS8EncodedKeySpec() {
byte[] encodedKey = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };
EncodedKeySpec eks = new PKCS8EncodedKeySpec(encodedKey);
assertTrue(eks instanceof PKCS8EncodedKeySpec);
try {
eks = new PKCS8EncodedKeySpec(null);
fail("expected NullPointerException");
} catch (NullPointerException e) {
}
}Example 59
| Project: android_platform_libcore-master File: PKCS8EncodedKeySpecTest.java View source code |
//
// Tests
//
/**
* Test for <code>PKCS8EncodedKeySpec</code> constructor<br>
* Assertion: constructs new <code>PKCS8EncodedKeySpec</code>
* object using valid parameter
*/
public final void testPKCS8EncodedKeySpec() {
byte[] encodedKey = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };
EncodedKeySpec eks = new PKCS8EncodedKeySpec(encodedKey);
assertTrue(eks instanceof PKCS8EncodedKeySpec);
try {
eks = new PKCS8EncodedKeySpec(null);
fail("expected NullPointerException");
} catch (NullPointerException e) {
}
}Example 60
| Project: ARTPart-master File: PKCS8EncodedKeySpecTest.java View source code |
//
// Tests
//
/**
* Test for <code>PKCS8EncodedKeySpec</code> constructor<br>
* Assertion: constructs new <code>PKCS8EncodedKeySpec</code>
* object using valid parameter
*/
public final void testPKCS8EncodedKeySpec() {
byte[] encodedKey = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };
EncodedKeySpec eks = new PKCS8EncodedKeySpec(encodedKey);
assertTrue(eks instanceof PKCS8EncodedKeySpec);
try {
eks = new PKCS8EncodedKeySpec(null);
fail("expected NullPointerException");
} catch (NullPointerException e) {
}
}Example 61
| Project: Assignments-master File: XadesTest.java View source code |
@Test
public void XadesBesRsaCert() throws Exception {
(new File(DestDirBes)).mkdirs();
super.initialize();
String filename = "xfa.signed.xades-bes.pdf";
String output = DestDirBes + filename;
BouncyCastleProvider provider = new BouncyCastleProvider();
Security.addProvider(provider);
CertificateFactory cf = CertificateFactory.getInstance("X509");
Certificate cert = cf.generateCertificate(new FileInputStream(CERTIFICATE));
Certificate[] chain = new Certificate[] { cert };
// Read Private Key.
File filePrivateKey = new File(KEYSTORE);
FileInputStream fis = new FileInputStream(KEYSTORE);
byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
fis.read(encodedPrivateKey);
fis.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
PrivateKey pk = keyFactory.generatePrivate(privateKeySpec);
signXadesWithCertificate(Src, output, pk, chain, DigestAlgorithms.SHA1, provider.getName(), false);
String cmp = saveXmlFromResult(output);
Assert.assertTrue("Verification", verifyXmlDSig(cmp));
}Example 62
| Project: atlas-lb-master File: KeyFactory.java View source code |
protected KeySpec engineGetKeySpec(Key key, Class spec) throws InvalidKeySpecException {
if (spec.isAssignableFrom(PKCS8EncodedKeySpec.class) && key.getFormat().equals("PKCS#8")) {
return new PKCS8EncodedKeySpec(key.getEncoded());
} else if (spec.isAssignableFrom(X509EncodedKeySpec.class) && key.getFormat().equals("X.509")) {
return new X509EncodedKeySpec(key.getEncoded());
} else if (spec.isAssignableFrom(java.security.spec.ECPublicKeySpec.class) && key instanceof ECPublicKey) {
ECPublicKey k = (ECPublicKey) key;
if (k.getParams() != null) {
return new java.security.spec.ECPublicKeySpec(k.getW(), k.getParams());
} else {
ECParameterSpec implicitSpec = ProviderUtil.getEcImplicitlyCa();
return new java.security.spec.ECPublicKeySpec(k.getW(), EC5Util.convertSpec(EC5Util.convertCurve(implicitSpec.getCurve(), implicitSpec.getSeed()), implicitSpec));
}
} else if (spec.isAssignableFrom(java.security.spec.ECPrivateKeySpec.class) && key instanceof ECPrivateKey) {
ECPrivateKey k = (ECPrivateKey) key;
if (k.getParams() != null) {
return new java.security.spec.ECPrivateKeySpec(k.getS(), k.getParams());
} else {
ECParameterSpec implicitSpec = ProviderUtil.getEcImplicitlyCa();
return new java.security.spec.ECPrivateKeySpec(k.getS(), EC5Util.convertSpec(EC5Util.convertCurve(implicitSpec.getCurve(), implicitSpec.getSeed()), implicitSpec));
}
}
throw new RuntimeException("not implemented yet " + key + " " + spec);
}Example 63
| Project: bigdo-master File: Rsa.java View source code |
public static String sign(String content, String privateKey) {
String charset = "UTF-8";
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 64
| Project: cloudbreak-master File: KeyStoreUtil.java View source code |
private static KeyPair loadPrivateKey(final String clientKeyPath) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
File privateKeyFile = new File(clientKeyPath);
BufferedReader reader = null;
PEMParser pemParser = null;
try {
reader = new BufferedReader(new FileReader(privateKeyFile));
pemParser = new PEMParser(reader);
PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
byte[] pemPrivateKeyEncoded = pemKeyPair.getPrivateKeyInfo().getEncoded();
byte[] pemPublicKeyEncoded = pemKeyPair.getPublicKeyInfo().getEncoded();
KeyFactory factory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pemPublicKeyEncoded);
PublicKey publicKey = factory.generatePublic(publicKeySpec);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pemPrivateKeyEncoded);
PrivateKey privateKey = factory.generatePrivate(privateKeySpec);
return new KeyPair(publicKey, privateKey);
} finally {
if (pemParser != null) {
pemParser.close();
}
if (reader != null) {
reader.close();
}
}
}Example 65
| Project: cs-244-project-master File: PBFTServerInstanceRunner.java View source code |
private static PrivateKey readPrivateKeyFromFile(File file) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException {
KeyFactory keyFactory = KeyFactory.getInstance(CryptoUtil.ALGORITHM);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] keyBytes = new byte[(int) file.length()];
fileInputStream.read(keyBytes);
return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
}Example 66
| Project: de.persosim.simulator-master File: KeyConverter.java View source code |
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
PrivateKey sk = null;
PublicKey pk = null;
getValuesFromXML(reader, context);
if (byteValue == null || algorithmValue == null || algorithmValue.equals("") || byteValue.equals("")) {
log(getClass(), "can not create " + keyType + " object, unmarshal failed", ERROR);
throw new XStreamException("can not create " + keyType + " object, unmarshal failed!");
}
PKCS8EncodedKeySpec ks_priv = new PKCS8EncodedKeySpec(HexString.toByteArray(byteValue));
X509EncodedKeySpec ks_pub = new X509EncodedKeySpec(HexString.toByteArray(byteValue));
//XXX split into private and public key converters
try {
pk = KeyFactory.getInstance(algorithmValue, Crypto.getCryptoProvider()).generatePublic(ks_pub);
} catch (InvalidKeySpecExceptionNoSuchAlgorithmException | e1) {
log(getClass(), "this is not a valid public key", DEBUG);
try {
sk = KeyFactory.getInstance(algorithmValue, Crypto.getCryptoProvider()).generatePrivate(ks_priv);
} catch (InvalidKeySpecExceptionNoSuchAlgorithmException | e2) {
log(getClass(), "this is also not a valid private key", DEBUG);
throw new XStreamException("Neither a valid private nor public key could be extracted", e2);
}
}
if (pk != null) {
return pk;
} else {
return sk;
}
}Example 67
| Project: EasyRecharge-master File: Rsa.java View source code |
public static String sign(String content, String privateKey) {
String charset = "UTF-8";
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 68
| Project: GaoRenZhiLu-master File: Rsa.java View source code |
public static String sign(String content, String privateKey) {
String charset = "UTF-8";
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 69
| Project: gocd-master File: RegistrationJSONizer.java View source code |
public static Registration fromJson(String json) {
Map map = GSON.fromJson(json, Map.class);
if (map.isEmpty()) {
return Registration.createNullPrivateKeyEntry();
}
List<Certificate> chain = new ArrayList<>();
try {
PemReader reader = new PemReader(new StringReader((String) map.get("agentPrivateKey")));
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(reader.readPemObject().getContent());
PrivateKey privateKey = kf.generatePrivate(spec);
String agentCertificate = (String) map.get("agentCertificate");
PemReader certReader = new PemReader(new StringReader(agentCertificate));
while (true) {
PemObject obj = certReader.readPemObject();
if (obj == null) {
break;
}
chain.add(CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(obj.getContent())));
}
return new Registration(privateKey, chain.toArray(new Certificate[chain.size()]));
} catch (IOExceptionNoSuchAlgorithmException | CertificateException | InvalidKeySpecException | e) {
throw bomb(e);
}
}Example 70
| Project: graylog2-server-master File: PemKeyStoreTest.java View source code |
@Test
public void testGenerateKeySpec() throws Exception {
final URL url = Resources.getResource("org/graylog2/shared/security/tls/private.key");
final byte[] privateKey = PemReader.readPrivateKey(Paths.get(url.toURI()));
final PKCS8EncodedKeySpec keySpec = PemKeyStore.generateKeySpec(null, privateKey);
assertThat(keySpec.getFormat()).isEqualTo("PKCS#8");
assertThat(keySpec.getEncoded()).isEqualTo(privateKey);
}Example 71
| Project: j360-master File: RSA.java View source code |
/**
* RSAç¾å??
* @param content å¾…ç¾å??æ•°æ?®
* @param privateKey 商户�钥
* @param input_charset ç¼–ç ?æ ¼å¼?
* @return ç¾å??值
*/
public static String sign(String content, String privateKey, String input_charset) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(input_charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 72
| Project: JAirPort-master File: Utils.java View source code |
private static Key getKey() {
try {
InputStream fis = ClassLoader.getSystemResourceAsStream("key.pk8");
if (fis == null) {
throw new RuntimeException("Cannot find keyfile");
}
try {
// openssl pkcs8 -inform pem -outform der -topk8 -nocrypt -in key.pem -out key.pk8
return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(getByteArrayFromStream(fis)));
} finally {
fis.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 73
| Project: mmmmggggwwwww-master File: Rsa.java View source code |
public static String sign(String content, String privateKey) {
String charset = "UTF-8";
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 74
| Project: MongoDBClusterTool-master File: SSHKey.java View source code |
public String getSSHPrivateKey() {
StringBuilder sb = new StringBuilder();
byte[] privateKeyBytes = new PKCS8EncodedKeySpec(encodePrivateKey(this.keyPair)).getEncoded();
String privateKey = new String(Base64.getEncoder().encode(privateKeyBytes));
String ls = System.getProperty("line.separator");
sb.append(PRIVATE_PKCS8_MARKER).append(ls);
sb.append(Joiner.on(ls).join(Splitter.fixedLength(64).split(privateKey))).append(ls);
sb.append(PRIVATE_PKCS8_MARKER.replace("BEGIN", "END")).append(ls);
return sb.toString();
}Example 75
| Project: OpenDolphin-master File: IdentityService.java View source code |
private RSAPrivateKey getPrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final byte[] encodedKey = readPrivateKeyFromDisk(layerConfig.getRsaKeyPath());
final EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
final PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
return (RSAPrivateKey) privateKey;
}Example 76
| Project: openjdk-master File: DSAKeyFactory.java View source code |
/**
* Generates a private key object from the provided key specification
* (key material).
*
* @param keySpec the specification (key material) of the private key
*
* @return the private key
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this key factory to produce a private key.
*/
protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException {
try {
if (keySpec instanceof DSAPrivateKeySpec) {
DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec) keySpec;
return new DSAPrivateKey(dsaPrivKeySpec.getX(), dsaPrivKeySpec.getP(), dsaPrivKeySpec.getQ(), dsaPrivKeySpec.getG());
} else if (keySpec instanceof PKCS8EncodedKeySpec) {
return new DSAPrivateKey(((PKCS8EncodedKeySpec) keySpec).getEncoded());
} else {
throw new InvalidKeySpecException("Inappropriate key specification");
}
} catch (InvalidKeyException e) {
throw new InvalidKeySpecException("Inappropriate key specification: " + e.getMessage());
}
}Example 77
| Project: orbeon-forms-master File: SignatureProcessor.java View source code |
public void readImpl(PipelineContext context, final XMLReceiver xmlReceiver) {
try {
final Document privDoc = readCacheInputAsDOM4J(context, INPUT_PRIVATE_KEY);
final String privString = XPathUtils.selectStringValueNormalize(privDoc, "/private-key");
final byte[] privBytes = Base64.decode(privString);
final PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privBytes);
final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
final PrivateKey privKey = keyFactory.generatePrivate(privKeySpec);
final Signature dsa = Signature.getInstance("SHA1withDSA");
dsa.initSign(privKey);
xmlReceiver.startDocument();
xmlReceiver.startElement("", SIGNED_DATA_ELEMENT, SIGNED_DATA_ELEMENT, SAXUtils.EMPTY_ATTRIBUTES);
xmlReceiver.startElement("", DATA_ELEMENT, DATA_ELEMENT, SAXUtils.EMPTY_ATTRIBUTES);
final Document data = readCacheInputAsDOM4J(context, INPUT_DATA);
final String dataStr = Dom4jUtils.domToString(data);
dsa.update(dataStr.getBytes("utf-8"));
final String sig = Base64.encode(dsa.sign(), true);
final LocationSAXWriter saxw = new LocationSAXWriter();
saxw.setContentHandler(xmlReceiver);
saxw.write(data.getRootElement());
xmlReceiver.endElement("", DATA_ELEMENT, DATA_ELEMENT);
xmlReceiver.startElement("", SIGNATURE_ELEMENT, SIGNATURE_ELEMENT, SAXUtils.EMPTY_ATTRIBUTES);
char[] sigChars = new char[sig.length()];
sig.getChars(0, sig.length(), sigChars, 0);
xmlReceiver.characters(sigChars, 0, sigChars.length);
xmlReceiver.endElement("", SIGNATURE_ELEMENT, SIGNATURE_ELEMENT);
xmlReceiver.endElement("", SIGNED_DATA_ELEMENT, SIGNED_DATA_ELEMENT);
xmlReceiver.endDocument();
} catch (Exception e) {
throw new OXFException(e);
}
}Example 78
| Project: PayMap-master File: RSA.java View source code |
/**
* RSAç¾å??
*
* @param content å¾…ç¾å??æ•°æ?®
* @param privateKey 商户�钥
* @param input_charset ç¼–ç ?æ ¼å¼?
* @return ç¾å??值
*/
public static String sign(String content, String privateKey, String input_charset) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(input_charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 79
| Project: picketlink-master File: RSASignatureProvider.java View source code |
/**
* @see org.picketlink.json.jose.crypto.SignatureProvider#sign(byte[], org.picketlink.json.jose.crypto.Algorithm, byte[])
*/
public byte[] sign(byte[] data, Algorithm algorithm, byte[] key) {
try {
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
Signature signature = Signature.getInstance(algorithm.getAlgorithm());
signature.initSign(privateKey);
signature.update(data);
return signature.sign();
} catch (Exception e) {
throw MESSAGES.cryptoSignatureFailed(algorithm, e);
}
}Example 80
| Project: private_project_iparty-master File: Rsa.java View source code |
public static String sign(String content, String privateKey) {
String charset = "UTF-8";
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 81
| Project: votifier-master File: RSAIO.java View source code |
/**
* Saves the key pair to the disk.
*
* @param directory
* The directory to save to
* @param keyPair
* The key pair to save
* @throws Exception
* If an error occurs
*/
public static void save(File directory, KeyPair keyPair) throws Exception {
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Store the public key.
X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(publicKey.getEncoded());
FileOutputStream out = new FileOutputStream(directory + "/public.key");
out.write(DatatypeConverter.printBase64Binary(publicSpec.getEncoded()).getBytes());
out.close();
// Store the private key.
PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
out = new FileOutputStream(directory + "/private.key");
out.write(DatatypeConverter.printBase64Binary(privateSpec.getEncoded()).getBytes());
out.close();
}Example 82
| Project: Wawc-master File: Rsa.java View source code |
public static String sign(String content, String privateKey) {
String charset = "UTF-8";
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 83
| Project: ZaoKe-master File: Rsa.java View source code |
public static String sign(String content, String privateKey) {
String charset = "UTF-8";
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 84
| Project: classlib6-master File: KeyRep.java View source code |
/**
* Resolve the Key object.
*
* <p> This method supports three Type/format combinations:
* <ul>
* <li> Type.SECRET/"RAW" - returns a SecretKeySpec object
* constructed using encoded key bytes and algorithm
* <li> Type.PUBLIC/"X.509" - gets a KeyFactory instance for
* the key algorithm, constructs an X509EncodedKeySpec with the
* encoded key bytes, and generates a public key from the spec
* <li> Type.PRIVATE/"PKCS#8" - gets a KeyFactory instance for
* the key algorithm, constructs a PKCS8EncodedKeySpec with the
* encoded key bytes, and generates a private key from the spec
* </ul>
*
* <p>
*
* @return the resolved Key object
*
* @exception ObjectStreamException if the Type/format
* combination is unrecognized, if the algorithm, key format, or
* encoded key bytes are unrecognized/invalid, of if the
* resolution of the key fails for any reason
*/
protected Object readResolve() throws ObjectStreamException {
try {
if (type == Type.SECRET && RAW.equals(format)) {
return new SecretKeySpec(encoded, algorithm);
} else if (type == Type.PUBLIC && X509.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePublic(new X509EncodedKeySpec(encoded));
} else if (type == Type.PRIVATE && PKCS8.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePrivate(new PKCS8EncodedKeySpec(encoded));
} else {
throw new NotSerializableException("unrecognized type/format combination: " + type + "/" + format);
}
} catch (NotSerializableException nse) {
throw nse;
} catch (Exception e) {
NotSerializableException nse = new NotSerializableException("java.security.Key: " + "[" + type + "] " + "[" + algorithm + "] " + "[" + format + "]");
nse.initCause(e);
throw nse;
}
}Example 85
| Project: ikvm-openjdk-master File: KeyRep.java View source code |
/**
* Resolve the Key object.
*
* <p> This method supports three Type/format combinations:
* <ul>
* <li> Type.SECRET/"RAW" - returns a SecretKeySpec object
* constructed using encoded key bytes and algorithm
* <li> Type.PUBLIC/"X.509" - gets a KeyFactory instance for
* the key algorithm, constructs an X509EncodedKeySpec with the
* encoded key bytes, and generates a public key from the spec
* <li> Type.PRIVATE/"PKCS#8" - gets a KeyFactory instance for
* the key algorithm, constructs a PKCS8EncodedKeySpec with the
* encoded key bytes, and generates a private key from the spec
* </ul>
*
* <p>
*
* @return the resolved Key object
*
* @exception ObjectStreamException if the Type/format
* combination is unrecognized, if the algorithm, key format, or
* encoded key bytes are unrecognized/invalid, of if the
* resolution of the key fails for any reason
*/
protected Object readResolve() throws ObjectStreamException {
try {
if (type == Type.SECRET && RAW.equals(format)) {
return new SecretKeySpec(encoded, algorithm);
} else if (type == Type.PUBLIC && X509.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePublic(new X509EncodedKeySpec(encoded));
} else if (type == Type.PRIVATE && PKCS8.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePrivate(new PKCS8EncodedKeySpec(encoded));
} else {
throw new NotSerializableException("unrecognized type/format combination: " + type + "/" + format);
}
} catch (NotSerializableException nse) {
throw nse;
} catch (Exception e) {
NotSerializableException nse = new NotSerializableException("java.security.Key: " + "[" + type + "] " + "[" + algorithm + "] " + "[" + format + "]");
nse.initCause(e);
throw nse;
}
}Example 86
| Project: j2objc-master File: KeyRep.java View source code |
/**
* Resolve the Key object.
*
* <p> This method supports three Type/format combinations:
* <ul>
* <li> Type.SECRET/"RAW" - returns a SecretKeySpec object
* constructed using encoded key bytes and algorithm
* <li> Type.PUBLIC/"X.509" - gets a KeyFactory instance for
* the key algorithm, constructs an X509EncodedKeySpec with the
* encoded key bytes, and generates a public key from the spec
* <li> Type.PRIVATE/"PKCS#8" - gets a KeyFactory instance for
* the key algorithm, constructs a PKCS8EncodedKeySpec with the
* encoded key bytes, and generates a private key from the spec
* </ul>
*
* <p>
*
* @return the resolved Key object
*
* @exception ObjectStreamException if the Type/format
* combination is unrecognized, if the algorithm, key format, or
* encoded key bytes are unrecognized/invalid, of if the
* resolution of the key fails for any reason
*/
protected Object readResolve() throws ObjectStreamException {
try {
if (type == Type.SECRET && RAW.equals(format)) {
return new SecretKeySpec(encoded, algorithm);
} else if (type == Type.PUBLIC && X509.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePublic(new X509EncodedKeySpec(encoded));
} else if (type == Type.PRIVATE && PKCS8.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePrivate(new PKCS8EncodedKeySpec(encoded));
} else {
throw new NotSerializableException("unrecognized type/format combination: " + type + "/" + format);
}
} catch (NotSerializableException nse) {
throw nse;
} catch (Exception e) {
NotSerializableException nse = new NotSerializableException("java.security.Key: " + "[" + type + "] " + "[" + algorithm + "] " + "[" + format + "]");
nse.initCause(e);
throw nse;
}
}Example 87
| Project: jdk7u-jdk-master File: KeyRep.java View source code |
/**
* Resolve the Key object.
*
* <p> This method supports three Type/format combinations:
* <ul>
* <li> Type.SECRET/"RAW" - returns a SecretKeySpec object
* constructed using encoded key bytes and algorithm
* <li> Type.PUBLIC/"X.509" - gets a KeyFactory instance for
* the key algorithm, constructs an X509EncodedKeySpec with the
* encoded key bytes, and generates a public key from the spec
* <li> Type.PRIVATE/"PKCS#8" - gets a KeyFactory instance for
* the key algorithm, constructs a PKCS8EncodedKeySpec with the
* encoded key bytes, and generates a private key from the spec
* </ul>
*
* <p>
*
* @return the resolved Key object
*
* @exception ObjectStreamException if the Type/format
* combination is unrecognized, if the algorithm, key format, or
* encoded key bytes are unrecognized/invalid, of if the
* resolution of the key fails for any reason
*/
protected Object readResolve() throws ObjectStreamException {
try {
if (type == Type.SECRET && RAW.equals(format)) {
return new SecretKeySpec(encoded, algorithm);
} else if (type == Type.PUBLIC && X509.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePublic(new X509EncodedKeySpec(encoded));
} else if (type == Type.PRIVATE && PKCS8.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePrivate(new PKCS8EncodedKeySpec(encoded));
} else {
throw new NotSerializableException("unrecognized type/format combination: " + type + "/" + format);
}
} catch (NotSerializableException nse) {
throw nse;
} catch (Exception e) {
NotSerializableException nse = new NotSerializableException("java.security.Key: " + "[" + type + "] " + "[" + algorithm + "] " + "[" + format + "]");
nse.initCause(e);
throw nse;
}
}Example 88
| Project: ManagedRuntimeInitiative-master File: KeyRep.java View source code |
/**
* Resolve the Key object.
*
* <p> This method supports three Type/format combinations:
* <ul>
* <li> Type.SECRET/"RAW" - returns a SecretKeySpec object
* constructed using encoded key bytes and algorithm
* <li> Type.PUBLIC/"X.509" - gets a KeyFactory instance for
* the key algorithm, constructs an X509EncodedKeySpec with the
* encoded key bytes, and generates a public key from the spec
* <li> Type.PRIVATE/"PKCS#8" - gets a KeyFactory instance for
* the key algorithm, constructs a PKCS8EncodedKeySpec with the
* encoded key bytes, and generates a private key from the spec
* </ul>
*
* <p>
*
* @return the resolved Key object
*
* @exception ObjectStreamException if the Type/format
* combination is unrecognized, if the algorithm, key format, or
* encoded key bytes are unrecognized/invalid, of if the
* resolution of the key fails for any reason
*/
protected Object readResolve() throws ObjectStreamException {
try {
if (type == Type.SECRET && RAW.equals(format)) {
return new SecretKeySpec(encoded, algorithm);
} else if (type == Type.PUBLIC && X509.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePublic(new X509EncodedKeySpec(encoded));
} else if (type == Type.PRIVATE && PKCS8.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePrivate(new PKCS8EncodedKeySpec(encoded));
} else {
throw new NotSerializableException("unrecognized type/format combination: " + type + "/" + format);
}
} catch (NotSerializableException nse) {
throw nse;
} catch (Exception e) {
NotSerializableException nse = new NotSerializableException("java.security.Key: " + "[" + type + "] " + "[" + algorithm + "] " + "[" + format + "]");
nse.initCause(e);
throw nse;
}
}Example 89
| Project: openjdk8-jdk-master File: KeyRep.java View source code |
/**
* Resolve the Key object.
*
* <p> This method supports three Type/format combinations:
* <ul>
* <li> Type.SECRET/"RAW" - returns a SecretKeySpec object
* constructed using encoded key bytes and algorithm
* <li> Type.PUBLIC/"X.509" - gets a KeyFactory instance for
* the key algorithm, constructs an X509EncodedKeySpec with the
* encoded key bytes, and generates a public key from the spec
* <li> Type.PRIVATE/"PKCS#8" - gets a KeyFactory instance for
* the key algorithm, constructs a PKCS8EncodedKeySpec with the
* encoded key bytes, and generates a private key from the spec
* </ul>
*
* <p>
*
* @return the resolved Key object
*
* @exception ObjectStreamException if the Type/format
* combination is unrecognized, if the algorithm, key format, or
* encoded key bytes are unrecognized/invalid, of if the
* resolution of the key fails for any reason
*/
protected Object readResolve() throws ObjectStreamException {
try {
if (type == Type.SECRET && RAW.equals(format)) {
return new SecretKeySpec(encoded, algorithm);
} else if (type == Type.PUBLIC && X509.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePublic(new X509EncodedKeySpec(encoded));
} else if (type == Type.PRIVATE && PKCS8.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePrivate(new PKCS8EncodedKeySpec(encoded));
} else {
throw new NotSerializableException("unrecognized type/format combination: " + type + "/" + format);
}
} catch (NotSerializableException nse) {
throw nse;
} catch (Exception e) {
NotSerializableException nse = new NotSerializableException("java.security.Key: " + "[" + type + "] " + "[" + algorithm + "] " + "[" + format + "]");
nse.initCause(e);
throw nse;
}
}Example 90
| Project: phoneme-components-cdc-master File: DSAKeyFactory.java View source code |
/**
* Generates a private key object from the provided key specification
* (key material).
*
* @param keySpec the specification (key material) of the private key
*
* @return the private key
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this key factory to produce a private key.
*/
protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException {
try {
if (keySpec instanceof DSAPrivateKeySpec) {
DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec) keySpec;
return new DSAPrivateKey(dsaPrivKeySpec.getX(), dsaPrivKeySpec.getP(), dsaPrivKeySpec.getQ(), dsaPrivKeySpec.getG());
} else if (keySpec instanceof PKCS8EncodedKeySpec) {
return new DSAPrivateKey(((PKCS8EncodedKeySpec) keySpec).getEncoded());
} else {
throw new InvalidKeySpecException("Inappropriate key specification");
}
} catch (InvalidKeyException e) {
throw new InvalidKeySpecException("Inappropriate key specification: " + e.getMessage());
}
}Example 91
| Project: property-db-master File: KeyRep.java View source code |
/** {@collect.stats}
* Resolve the Key object.
*
* <p> This method supports three Type/format combinations:
* <ul>
* <li> Type.SECRET/"RAW" - returns a SecretKeySpec object
* constructed using encoded key bytes and algorithm
* <li> Type.PUBLIC/"X.509" - gets a KeyFactory instance for
* the key algorithm, constructs an X509EncodedKeySpec with the
* encoded key bytes, and generates a public key from the spec
* <li> Type.PRIVATE/"PKCS#8" - gets a KeyFactory instance for
* the key algorithm, constructs a PKCS8EncodedKeySpec with the
* encoded key bytes, and generates a private key from the spec
* </ul>
*
* <p>
*
* @return the resolved Key object
*
* @exception ObjectStreamException if the Type/format
* combination is unrecognized, if the algorithm, key format, or
* encoded key bytes are unrecognized/invalid, of if the
* resolution of the key fails for any reason
*/
protected Object readResolve() throws ObjectStreamException {
try {
if (type == Type.SECRET && RAW.equals(format)) {
return new SecretKeySpec(encoded, algorithm);
} else if (type == Type.PUBLIC && X509.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePublic(new X509EncodedKeySpec(encoded));
} else if (type == Type.PRIVATE && PKCS8.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePrivate(new PKCS8EncodedKeySpec(encoded));
} else {
throw new NotSerializableException("unrecognized type/format combination: " + type + "/" + format);
}
} catch (NotSerializableException nse) {
throw nse;
} catch (Exception e) {
NotSerializableException nse = new NotSerializableException("java.security.Key: " + "[" + type + "] " + "[" + algorithm + "] " + "[" + format + "]");
nse.initCause(e);
throw nse;
}
}Example 92
| Project: android-sdk-sources-for-api-level-23-master File: AndroidKeyStoreKeyFactorySpi.java View source code |
@Override
protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpecClass) throws InvalidKeySpecException {
if (key == null) {
throw new InvalidKeySpecException("key == null");
} else if ((!(key instanceof AndroidKeyStorePrivateKey)) && (!(key instanceof AndroidKeyStorePublicKey))) {
throw new InvalidKeySpecException("Unsupported key type: " + key.getClass().getName() + ". This KeyFactory supports only Android Keystore asymmetric keys");
}
if (keySpecClass == null) {
throw new InvalidKeySpecException("keySpecClass == null");
} else if (KeyInfo.class.equals(keySpecClass)) {
if (!(key instanceof AndroidKeyStorePrivateKey)) {
throw new InvalidKeySpecException("Unsupported key type: " + key.getClass().getName() + ". KeyInfo can be obtained only for Android Keystore private keys");
}
String keyAliasInKeystore = ((AndroidKeyStorePrivateKey) key).getAlias();
String entryAlias;
if (keyAliasInKeystore.startsWith(Credentials.USER_PRIVATE_KEY)) {
entryAlias = keyAliasInKeystore.substring(Credentials.USER_PRIVATE_KEY.length());
} else {
throw new InvalidKeySpecException("Invalid key alias: " + keyAliasInKeystore);
}
@SuppressWarnings("unchecked") T result = (T) AndroidKeyStoreSecretKeyFactorySpi.getKeyInfo(mKeyStore, entryAlias, keyAliasInKeystore);
return result;
} else if (X509EncodedKeySpec.class.equals(keySpecClass)) {
if (!(key instanceof AndroidKeyStorePublicKey)) {
throw new InvalidKeySpecException("Unsupported key type: " + key.getClass().getName() + ". X509EncodedKeySpec can be obtained only for Android Keystore public" + " keys");
}
@SuppressWarnings("unchecked") T result = (T) new X509EncodedKeySpec(((AndroidKeyStorePublicKey) key).getEncoded());
return result;
} else if (PKCS8EncodedKeySpec.class.equals(keySpecClass)) {
if (key instanceof AndroidKeyStorePrivateKey) {
throw new InvalidKeySpecException("Key material export of Android Keystore private keys is not supported");
} else {
throw new InvalidKeySpecException("Cannot export key material of public key in PKCS#8 format." + " Only X.509 format (X509EncodedKeySpec) supported for public keys.");
}
} else if (RSAPublicKeySpec.class.equals(keySpecClass)) {
if (key instanceof AndroidKeyStoreRSAPublicKey) {
AndroidKeyStoreRSAPublicKey rsaKey = (AndroidKeyStoreRSAPublicKey) key;
@SuppressWarnings("unchecked") T result = (T) new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent());
return result;
} else {
throw new InvalidKeySpecException("Obtaining RSAPublicKeySpec not supported for " + key.getAlgorithm() + " " + ((key instanceof AndroidKeyStorePrivateKey) ? "private" : "public") + " key");
}
} else if (ECPublicKeySpec.class.equals(keySpecClass)) {
if (key instanceof AndroidKeyStoreECPublicKey) {
AndroidKeyStoreECPublicKey ecKey = (AndroidKeyStoreECPublicKey) key;
@SuppressWarnings("unchecked") T result = (T) new ECPublicKeySpec(ecKey.getW(), ecKey.getParams());
return result;
} else {
throw new InvalidKeySpecException("Obtaining ECPublicKeySpec not supported for " + key.getAlgorithm() + " " + ((key instanceof AndroidKeyStorePrivateKey) ? "private" : "public") + " key");
}
} else {
throw new InvalidKeySpecException("Unsupported key spec: " + keySpecClass.getName());
}
}Example 93
| Project: android_frameworks_base-master File: AndroidKeyStoreKeyFactorySpi.java View source code |
@Override
protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpecClass) throws InvalidKeySpecException {
if (key == null) {
throw new InvalidKeySpecException("key == null");
} else if ((!(key instanceof AndroidKeyStorePrivateKey)) && (!(key instanceof AndroidKeyStorePublicKey))) {
throw new InvalidKeySpecException("Unsupported key type: " + key.getClass().getName() + ". This KeyFactory supports only Android Keystore asymmetric keys");
}
if (keySpecClass == null) {
throw new InvalidKeySpecException("keySpecClass == null");
} else if (KeyInfo.class.equals(keySpecClass)) {
if (!(key instanceof AndroidKeyStorePrivateKey)) {
throw new InvalidKeySpecException("Unsupported key type: " + key.getClass().getName() + ". KeyInfo can be obtained only for Android Keystore private keys");
}
AndroidKeyStorePrivateKey keystorePrivateKey = (AndroidKeyStorePrivateKey) key;
String keyAliasInKeystore = keystorePrivateKey.getAlias();
String entryAlias;
if (keyAliasInKeystore.startsWith(Credentials.USER_PRIVATE_KEY)) {
entryAlias = keyAliasInKeystore.substring(Credentials.USER_PRIVATE_KEY.length());
} else {
throw new InvalidKeySpecException("Invalid key alias: " + keyAliasInKeystore);
}
@SuppressWarnings("unchecked") T result = (T) AndroidKeyStoreSecretKeyFactorySpi.getKeyInfo(mKeyStore, entryAlias, keyAliasInKeystore, keystorePrivateKey.getUid());
return result;
} else if (X509EncodedKeySpec.class.equals(keySpecClass)) {
if (!(key instanceof AndroidKeyStorePublicKey)) {
throw new InvalidKeySpecException("Unsupported key type: " + key.getClass().getName() + ". X509EncodedKeySpec can be obtained only for Android Keystore public" + " keys");
}
@SuppressWarnings("unchecked") T result = (T) new X509EncodedKeySpec(((AndroidKeyStorePublicKey) key).getEncoded());
return result;
} else if (PKCS8EncodedKeySpec.class.equals(keySpecClass)) {
if (key instanceof AndroidKeyStorePrivateKey) {
throw new InvalidKeySpecException("Key material export of Android Keystore private keys is not supported");
} else {
throw new InvalidKeySpecException("Cannot export key material of public key in PKCS#8 format." + " Only X.509 format (X509EncodedKeySpec) supported for public keys.");
}
} else if (RSAPublicKeySpec.class.equals(keySpecClass)) {
if (key instanceof AndroidKeyStoreRSAPublicKey) {
AndroidKeyStoreRSAPublicKey rsaKey = (AndroidKeyStoreRSAPublicKey) key;
@SuppressWarnings("unchecked") T result = (T) new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent());
return result;
} else {
throw new InvalidKeySpecException("Obtaining RSAPublicKeySpec not supported for " + key.getAlgorithm() + " " + ((key instanceof AndroidKeyStorePrivateKey) ? "private" : "public") + " key");
}
} else if (ECPublicKeySpec.class.equals(keySpecClass)) {
if (key instanceof AndroidKeyStoreECPublicKey) {
AndroidKeyStoreECPublicKey ecKey = (AndroidKeyStoreECPublicKey) key;
@SuppressWarnings("unchecked") T result = (T) new ECPublicKeySpec(ecKey.getW(), ecKey.getParams());
return result;
} else {
throw new InvalidKeySpecException("Obtaining ECPublicKeySpec not supported for " + key.getAlgorithm() + " " + ((key instanceof AndroidKeyStorePrivateKey) ? "private" : "public") + " key");
}
} else {
throw new InvalidKeySpecException("Unsupported key spec: " + keySpecClass.getName());
}
}Example 94
| Project: authentication-master File: KeyCodecTest.java View source code |
@Test
public void test() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, IOException, InvalidKeySpecException {
KeyPair keyPair = KeyCodec.getKeyPair();
PrivateKey privKey = keyPair.getPrivate();
byte[] encodedPrivKey = privKey.getEncoded();
logger.info("priv=" + Base64.encodeBase64URLSafeString(encodedPrivKey));
PublicKey pubKey = keyPair.getPublic();
byte[] encodedPubKey = pubKey.getEncoded();
logger.info("pub=" + Base64.encodeBase64URLSafeString(encodedPubKey));
KeyFactory kf = KeyFactory.getInstance("ECDSA", "BC");
PublicKey pubKey2 = kf.generatePublic(new X509EncodedKeySpec(encodedPubKey));
assertTrue(Arrays.equals(pubKey2.getEncoded(), encodedPubKey));
PrivateKey privKey2 = kf.generatePrivate(new PKCS8EncodedKeySpec(encodedPrivKey));
assertTrue(Arrays.equals(privKey2.getEncoded(), encodedPrivKey));
}Example 95
| Project: aws-java-sdk-master File: RSA.java View source code |
/**
* Returns a private key constructed from the given DER bytes in PKCS#8 format.
*/
public static PrivateKey privateKeyFromPKCS8(byte[] pkcs8) throws InvalidKeySpecException {
try {
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pkcs8);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
return privateKey;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}Example 96
| Project: aws-sdk-java-master File: RSA.java View source code |
/**
* Returns a private key constructed from the given DER bytes in PKCS#8 format.
*/
public static PrivateKey privateKeyFromPKCS8(byte[] pkcs8) throws InvalidKeySpecException {
try {
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pkcs8);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
return privateKey;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}Example 97
| Project: bergamot-master File: KeyUtil.java View source code |
public static KeyPair loadPrivateKey(File file) throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {
byte[] data = loadFile(file);
// unpack
ByteBuffer buf = ByteBuffer.wrap(data);
int pubLen = buf.getInt();
if (pubLen < 16 || pubLen > 8192)
throw new IOException("Bad key");
byte[] pub = new byte[pubLen];
buf.get(pub);
int prvLen = buf.getInt();
if (prvLen < 16 || prvLen > 8192)
throw new IOException("Bad key");
byte[] prv = new byte[prvLen];
buf.get(prv);
// load
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey prvKey = kf.generatePrivate(new PKCS8EncodedKeySpec(prv));
PublicKey pubKey = kf.generatePublic(new X509EncodedKeySpec(pub));
return new KeyPair(pubKey, prvKey);
}Example 98
| Project: cattle-master File: JwtTokenServiceImplTest.java View source code |
@Before
public void setUp() {
impl = new JwtTokenServiceImpl();
impl.setKeyProvider(new RSAKeyProvider() {
KeyFactory kf;
EncodedKeySpec spec = new PKCS8EncodedKeySpec(new Base64(KEY).decode());
@Override
public RSAPrivateKeyHolder getPrivateKey() {
try {
kf = KeyFactory.getInstance("RSA");
return new RSAPrivateKeyHolder("abc", (RSAPrivateKey) kf.generatePrivate(spec));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeySpecException e) {
throw new RuntimeException(e);
}
}
@Override
public Map<String, PublicKey> getPublicKeys() {
return null;
}
@Override
public PublicKey getDefaultPublicKey() {
try {
kf = KeyFactory.getInstance("RSA");
BigInteger modulus = new BigInteger("111477103238322465633334802347196848276745427190035850232359047430738831490294428792865542779043266665451160648116725279287065632589519313377918207473210865843357067938152969267052295101676828476867765239574399207781254529735105609482031252978262212237371891597488765482508817144842927535892383110624969098603");
BigInteger exponent = new BigInteger("65537");
RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(modulus, exponent);
return kf.generatePublic(publicKeySpec);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public CertSet generateCertificate(String subject, String... sans) throws Exception {
return null;
}
@Override
public Certificate getCACertificate() {
return null;
}
@Override
public byte[] toBytes(Certificate cert) throws IOException {
return null;
}
});
}Example 99
| Project: ceno-master File: Crypto.java View source code |
public static PrivateKey loadPrivateKey(String key64) throws GeneralSecurityException, IllegalBase64Exception {
byte[] clear = Base64.decodeStandard(key64);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);
KeyFactory fact = KeyFactory.getInstance(KEY_ALGORITHM, SECURITY_PROVIDER);
PrivateKey priv = fact.generatePrivate(keySpec);
Arrays.fill(clear, (byte) 0);
return priv;
}Example 100
| Project: che-master File: DockerCertificates.java View source code |
private static PrivateKey getPrivateKey(Path clientKeyPath) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
final PEMKeyPair clientKeyPair;
try (Reader reader = Files.newBufferedReader(clientKeyPath, Charset.defaultCharset())) {
clientKeyPair = (PEMKeyPair) new PEMParser(reader).readObject();
}
final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(clientKeyPair.getPrivateKeyInfo().getEncoded());
final KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}Example 101
| Project: che-plugins-master File: DockerCertificates.java View source code |
private static PrivateKey getPrivateKey(Path clientKeyPath) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
final PEMKeyPair clientKeyPair;
try (Reader reader = Files.newBufferedReader(clientKeyPath, Charset.defaultCharset())) {
clientKeyPair = (PEMKeyPair) new PEMParser(reader).readObject();
}
final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(clientKeyPair.getPrivateKeyInfo().getEncoded());
final KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}