use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project cdap by caskdata.
the class KeyStores method getCertificate.
/**
* Generate an X.509 certificate
*
* @param dn Distinguished name for the owner of the certificate, it will also be the signer of the certificate.
* @param pair Key pair used for signing the certificate.
* @param days Validity of the certificate.
* @param algorithm Name of the signature algorithm used.
* @return A X.509 certificate
*/
private static Certificate getCertificate(String dn, KeyPair pair, int days, String algorithm) throws IOException, OperatorCreationException, CertificateException {
BouncyCastleProvider provider = new BouncyCastleProvider();
// Calculate the validity interval of the certificate
Date from = new Date();
Date to = new Date(from.getTime() + TimeUnit.DAYS.toMillis(days));
// Generate a random number to use as the serial number for the certificate
BigInteger sn = new BigInteger(64, new SecureRandom());
// Create the name of the owner based on the provided distinguished name
X500Name owner = new X500Name(dn);
// Create an info objects with the provided information, which will be used to create the certificate
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
AsymmetricKeyParameter privateKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
ContentSigner signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyParam);
X509CertificateHolder certHolder = new X509v3CertificateBuilder(owner, sn, from, to, owner, publicKeyInfo).build(signer);
return new JcaX509CertificateConverter().setProvider(provider).getCertificate(certHolder);
}
use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project dpc-app by CMSgov.
the class PublicKeyHandlerTest method testEncryptionRoundTrip.
@Test
void testEncryptionRoundTrip() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException, InvalidKeySpecException {
final String plainText = "This should be encrypted";
final Cipher cipher = Cipher.getInstance("RSA");
final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
final KeyPair keyPair = kpg.generateKeyPair();
final String encoded = Base64.getMimeEncoder().encodeToString(keyPair.getPublic().getEncoded());
final String key = String.format("-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n", encoded);
final SubjectPublicKeyInfo publicKeyInfo = PublicKeyHandler.parsePEMString(key);
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());
final byte[] cipherText = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
// Reconstruct the public key and try to decrypt
X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyInfo.getEncoded());
final PublicKey rsa = KeyFactory.getInstance("RSA").generatePublic(spec);
cipher.init(Cipher.DECRYPT_MODE, rsa);
final byte[] decrypted = cipher.doFinal(cipherText);
assertEquals(plainText, new String(decrypted), "Should have matching plain text");
}
use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project aaa by opendaylight.
the class ODLKeyTool method createKeyStoreWithSelfSignCert.
/**
* Create a keystore that has self sign private/public keys.
*
* @param keyStoreName
* the keystore name
* @param keystorePassword
* the keystore password
* @param distinguishedName
* the generated key's Distinguished Name
* @param keyAlias
* the private key alias
* @param validity
* the key validity
* @param keyAlg
* the algorithm that will be used to generate the key
* @param keySize
* the key size
* @param signAlg
* the signing algorithm
* @return keystore object
*/
public KeyStore createKeyStoreWithSelfSignCert(final String keyStoreName, final String keystorePassword, final String distinguishedName, final String keyAlias, final int validity, final String keyAlg, final int keySize, final String signAlg) {
try {
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlg);
keyPairGenerator.initialize(keySize);
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
final long currTime = System.currentTimeMillis();
final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
final X509v3CertificateBuilder x509V3CertBuilder = new X509v3CertificateBuilder(new X500Name(distinguishedName), getSecureRandomeInt(), new Date(currTime), new Date(currTime + KeyStoreConstant.DAY_TIME * validity), new X500Name(distinguishedName), keyInfo);
final X509CertificateHolder x509Cert = x509V3CertBuilder.build(new JcaContentSignerBuilder(signAlg).build(keyPair.getPrivate()));
final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
ctlKeyStore.load(null, keystorePassword.toCharArray());
final Certificate[] chain = new Certificate[] { new JcaX509CertificateConverter().getCertificate(x509Cert) };
ctlKeyStore.setKeyEntry(keyAlias, keyPair.getPrivate(), keystorePassword.toCharArray(), chain);
LOG.info("{} is created", keyStoreName);
return ctlKeyStore;
} catch (final NoSuchAlgorithmException | SecurityException | KeyStoreException | CertificateException | IOException | OperatorCreationException e) {
LOG.error("Fatal error creating keystore", e);
return null;
}
}
use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project aaa by opendaylight.
the class ODLKeyTool method generateCertificateReq.
/**
* Generate a certificate signing request based on the given keystore
* private/public key.
*
* @param keyStore
* object
* @param keystorePassword
* the keystore password
* @param keyAlias
* Alias of the given keystore's private key.
* @param signAlg
* the signing algorithm
* @param withTag
* true to add the certificate request tag to the certificate
* request string.
* @return certificate request as string.
*/
public String generateCertificateReq(final KeyStore keyStore, final String keystorePassword, final String keyAlias, final String signAlg, final boolean withTag) {
try {
if (keyStore.containsAlias(keyAlias)) {
final X509Certificate odlCert = (X509Certificate) keyStore.getCertificate(keyAlias);
final PublicKey pubKey = odlCert.getPublicKey();
final PrivateKey privKey = (PrivateKey) keyStore.getKey(keyAlias, keystorePassword.toCharArray());
final String subject = odlCert.getSubjectDN().getName();
final X500Name xName = new X500Name(subject);
final SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded());
final PKCS10CertificationRequestBuilder csrb = new PKCS10CertificationRequestBuilder(xName, subPubKeyInfo);
final ContentSigner contSigner = new JcaContentSignerBuilder(signAlg).build(privKey);
final String certReq = Base64.getEncoder().encodeToString(csrb.build(contSigner).getEncoded());
return !withTag ? certReq : new StringBuilder().append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST).append('\n').append(certReq).append('\n').append(KeyStoreConstant.END_CERTIFICATE_REQUEST).toString();
}
LOG.info("KeyStore does not contain alias {}", keyAlias);
return StringUtils.EMPTY;
} catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | OperatorCreationException | IOException e) {
LOG.error("Failed to generate certificate request", e);
return StringUtils.EMPTY;
}
}
use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project jruby-openssl by jruby.
the class PKey method readECPrivateKey.
public static KeyPair readECPrivateKey(final KeyFactory ecFactory, final byte[] input) throws IOException, InvalidKeySpecException {
try {
ECPrivateKeyStructure pKey = new ECPrivateKeyStructure((ASN1Sequence) ASN1Primitive.fromByteArray(input));
AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParameters());
PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.toASN1Primitive());
SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pKey.getPublicKey().getBytes());
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privInfo.getEncoded());
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubInfo.getEncoded());
// KeyFactory fact = KeyFactory.getInstance("ECDSA", provider);
ECPrivateKey privateKey = (ECPrivateKey) ecFactory.generatePrivate(privSpec);
if (algId.getParameters() instanceof ASN1ObjectIdentifier) {
privateKey = ECPrivateKeyWithName.wrap(privateKey, (ASN1ObjectIdentifier) algId.getParameters());
}
return new KeyPair(ecFactory.generatePublic(pubSpec), privateKey);
} catch (ClassCastException ex) {
throw new IOException("wrong ASN.1 object found in stream", ex);
}
// catch (Exception ex) {
// throw new IOException("problem parsing EC private key: " + ex);
// }
}
Aggregations