use of java.security.PrivateKey in project platformlayer by platformlayer.
the class SimpleOpsKeyStore method loadAllKeys.
private void loadAllKeys(File dir) throws IOException {
if (!dir.exists()) {
return;
}
log.warn("Using (deprecated) system keys");
for (File file : dir.listFiles(new FilenameEndsWithFilter(".pub"))) {
PublicKey publicKey = RsaUtils.loadPublicKey(file);
String name = file.getName();
name = name.replace(".pub", "");
publicKeys.put(Integer.parseInt(name), publicKey);
}
for (File file : dir.listFiles(new FilenameEndsWithFilter(".private"))) {
PrivateKey privateKey = RsaUtils.loadPrivateKey(file);
String name = file.getName();
name = name.replace(".private", "");
privateKeys.put(Integer.parseInt(name), privateKey);
}
}
use of java.security.PrivateKey in project dex2jar by pxb1988.
the class ApkSign method doCommandLine.
@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, String relative) throws IOException {
Path target = outRoot.resolve(relative);
createParentDirectories(target);
Files.copy(file, target);
}
});
}
} else {
realJar = apkIn;
}
AbstractJarSign signer;
if (tiny) {
signer = new TinySignImpl();
} else {
try {
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"))));
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);
}
}
}
use of java.security.PrivateKey in project xabber-android by redsolution.
the class AccountTable method getKeyPair.
static KeyPair getKeyPair(Cursor cursor) {
byte[] publicKeyBytes = cursor.getBlob(cursor.getColumnIndex(Fields.PUBLIC_KEY));
byte[] privateKeyBytes = cursor.getBlob(cursor.getColumnIndex(Fields.PRIVATE_KEY));
if (privateKeyBytes == null || publicKeyBytes == null) {
return null;
}
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PublicKey publicKey;
PrivateKey privateKey;
KeyFactory keyFactory;
try {
keyFactory = KeyFactory.getInstance("DSA");
publicKey = keyFactory.generatePublic(publicKeySpec);
privateKey = keyFactory.generatePrivate(privateKeySpec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new RuntimeException(e);
}
return new KeyPair(publicKey, privateKey);
}
use of java.security.PrivateKey in project robovm by robovm.
the class PKCS12KeyStoreSpi method doStore.
private void doStore(OutputStream stream, char[] password, boolean useDEREncoding) throws IOException {
if (password == null) {
throw new NullPointerException("No password supplied for PKCS#12 KeyStore.");
}
//
// handle the key
//
ASN1EncodableVector keyS = new ASN1EncodableVector();
Enumeration ks = keys.keys();
while (ks.hasMoreElements()) {
byte[] kSalt = new byte[SALT_SIZE];
random.nextBytes(kSalt);
String name = (String) ks.nextElement();
PrivateKey privKey = (PrivateKey) keys.get(name);
PKCS12PBEParams kParams = new PKCS12PBEParams(kSalt, MIN_ITERATIONS);
byte[] kBytes = wrapKey(keyAlgorithm.getId(), privKey, kParams, password);
AlgorithmIdentifier kAlgId = new AlgorithmIdentifier(keyAlgorithm, kParams.toASN1Primitive());
org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo kInfo = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo(kAlgId, kBytes);
boolean attrSet = false;
ASN1EncodableVector kName = new ASN1EncodableVector();
if (privKey instanceof PKCS12BagAttributeCarrier) {
PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) privKey;
//
// make sure we are using the local alias on store
//
DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
if (nm == null || !nm.getString().equals(name)) {
bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
}
//
if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
Certificate ct = engineGetCertificate(name);
bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(ct.getPublicKey()));
}
Enumeration e = bagAttrs.getBagAttributeKeys();
while (e.hasMoreElements()) {
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
ASN1EncodableVector kSeq = new ASN1EncodableVector();
kSeq.add(oid);
kSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
attrSet = true;
kName.add(new DERSequence(kSeq));
}
}
if (!attrSet) {
//
// set a default friendly name (from the key id) and local id
//
ASN1EncodableVector kSeq = new ASN1EncodableVector();
Certificate ct = engineGetCertificate(name);
kSeq.add(pkcs_9_at_localKeyId);
kSeq.add(new DERSet(createSubjectKeyId(ct.getPublicKey())));
kName.add(new DERSequence(kSeq));
kSeq = new ASN1EncodableVector();
kSeq.add(pkcs_9_at_friendlyName);
kSeq.add(new DERSet(new DERBMPString(name)));
kName.add(new DERSequence(kSeq));
}
SafeBag kBag = new SafeBag(pkcs8ShroudedKeyBag, kInfo.toASN1Primitive(), new DERSet(kName));
keyS.add(kBag);
}
byte[] keySEncoded = new DERSequence(keyS).getEncoded(ASN1Encoding.DER);
BEROctetString keyString = new BEROctetString(keySEncoded);
//
// certificate processing
//
byte[] cSalt = new byte[SALT_SIZE];
random.nextBytes(cSalt);
ASN1EncodableVector certSeq = new ASN1EncodableVector();
PKCS12PBEParams cParams = new PKCS12PBEParams(cSalt, MIN_ITERATIONS);
AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.toASN1Primitive());
Hashtable doneCerts = new Hashtable();
Enumeration cs = keys.keys();
while (cs.hasMoreElements()) {
try {
String name = (String) cs.nextElement();
Certificate cert = engineGetCertificate(name);
boolean cAttrSet = false;
CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
ASN1EncodableVector fName = new ASN1EncodableVector();
if (cert instanceof PKCS12BagAttributeCarrier) {
PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
//
// make sure we are using the local alias on store
//
DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
if (nm == null || !nm.getString().equals(name)) {
bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
}
//
if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(cert.getPublicKey()));
}
Enumeration e = bagAttrs.getBagAttributeKeys();
while (e.hasMoreElements()) {
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(oid);
fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
fName.add(new DERSequence(fSeq));
cAttrSet = true;
}
}
if (!cAttrSet) {
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(pkcs_9_at_localKeyId);
fSeq.add(new DERSet(createSubjectKeyId(cert.getPublicKey())));
fName.add(new DERSequence(fSeq));
fSeq = new ASN1EncodableVector();
fSeq.add(pkcs_9_at_friendlyName);
fSeq.add(new DERSet(new DERBMPString(name)));
fName.add(new DERSequence(fSeq));
}
SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
certSeq.add(sBag);
doneCerts.put(cert, cert);
} catch (CertificateEncodingException e) {
throw new IOException("Error encoding certificate: " + e.toString());
}
}
cs = certs.keys();
while (cs.hasMoreElements()) {
try {
String certId = (String) cs.nextElement();
Certificate cert = (Certificate) certs.get(certId);
boolean cAttrSet = false;
if (keys.get(certId) != null) {
continue;
}
CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
ASN1EncodableVector fName = new ASN1EncodableVector();
if (cert instanceof PKCS12BagAttributeCarrier) {
PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
//
// make sure we are using the local alias on store
//
DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
if (nm == null || !nm.getString().equals(certId)) {
bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(certId));
}
Enumeration e = bagAttrs.getBagAttributeKeys();
while (e.hasMoreElements()) {
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
// If we find one, we'll prune it out.
if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
continue;
}
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(oid);
fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
fName.add(new DERSequence(fSeq));
cAttrSet = true;
}
}
if (!cAttrSet) {
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(pkcs_9_at_friendlyName);
fSeq.add(new DERSet(new DERBMPString(certId)));
fName.add(new DERSequence(fSeq));
}
SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
certSeq.add(sBag);
doneCerts.put(cert, cert);
} catch (CertificateEncodingException e) {
throw new IOException("Error encoding certificate: " + e.toString());
}
}
cs = chainCerts.keys();
while (cs.hasMoreElements()) {
try {
CertId certId = (CertId) cs.nextElement();
Certificate cert = (Certificate) chainCerts.get(certId);
if (doneCerts.get(cert) != null) {
continue;
}
CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
ASN1EncodableVector fName = new ASN1EncodableVector();
if (cert instanceof PKCS12BagAttributeCarrier) {
PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
Enumeration e = bagAttrs.getBagAttributeKeys();
while (e.hasMoreElements()) {
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
// If we find one, we'll prune it out.
if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
continue;
}
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(oid);
fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
fName.add(new DERSequence(fSeq));
}
}
SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
certSeq.add(sBag);
} catch (CertificateEncodingException e) {
throw new IOException("Error encoding certificate: " + e.toString());
}
}
byte[] certSeqEncoded = new DERSequence(certSeq).getEncoded(ASN1Encoding.DER);
byte[] certBytes = cryptData(true, cAlgId, password, false, certSeqEncoded);
EncryptedData cInfo = new EncryptedData(data, cAlgId, new BEROctetString(certBytes));
ContentInfo[] info = new ContentInfo[] { new ContentInfo(data, keyString), new ContentInfo(encryptedData, cInfo.toASN1Primitive()) };
AuthenticatedSafe auth = new AuthenticatedSafe(info);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
DEROutputStream asn1Out;
if (useDEREncoding) {
asn1Out = new DEROutputStream(bOut);
} else {
asn1Out = new BEROutputStream(bOut);
}
asn1Out.writeObject(auth);
byte[] pkg = bOut.toByteArray();
ContentInfo mainInfo = new ContentInfo(data, new BEROctetString(pkg));
//
// create the mac
//
byte[] mSalt = new byte[20];
int itCount = MIN_ITERATIONS;
random.nextBytes(mSalt);
byte[] data = ((ASN1OctetString) mainInfo.getContent()).getOctets();
MacData mData;
try {
byte[] res = calculatePbeMac(id_SHA1, mSalt, itCount, password, false, data);
AlgorithmIdentifier algId = new AlgorithmIdentifier(id_SHA1, DERNull.INSTANCE);
DigestInfo dInfo = new DigestInfo(algId, res);
mData = new MacData(dInfo, mSalt, itCount);
} catch (Exception e) {
throw new IOException("error constructing MAC: " + e.toString());
}
//
// output the Pfx
//
Pfx pfx = new Pfx(mainInfo, mData);
if (useDEREncoding) {
asn1Out = new DEROutputStream(stream);
} else {
asn1Out = new BEROutputStream(stream);
}
asn1Out.writeObject(pfx);
}
use of java.security.PrivateKey in project robovm by robovm.
the class PKCS12KeyStoreSpi method unwrapKey.
protected PrivateKey unwrapKey(AlgorithmIdentifier algId, byte[] data, char[] password, boolean wrongPKCS12Zero) throws IOException {
ASN1ObjectIdentifier algorithm = algId.getAlgorithm();
try {
if (algorithm.on(PKCSObjectIdentifiers.pkcs_12PbeIds)) {
PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algId.getParameters());
PBEKeySpec pbeSpec = new PBEKeySpec(password);
PrivateKey out;
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm.getId(), bcProvider);
PBEParameterSpec defParams = new PBEParameterSpec(pbeParams.getIV(), pbeParams.getIterations().intValue());
SecretKey k = keyFact.generateSecret(pbeSpec);
((BCPBEKey) k).setTryWrongPKCS12Zero(wrongPKCS12Zero);
Cipher cipher = Cipher.getInstance(algorithm.getId(), bcProvider);
cipher.init(Cipher.UNWRAP_MODE, k, defParams);
// we pass "" as the key algorithm type as it is unknown at this point
return (PrivateKey) cipher.unwrap(data, "", Cipher.PRIVATE_KEY);
} else if (algorithm.equals(PKCSObjectIdentifiers.id_PBES2)) {
PBES2Parameters alg = PBES2Parameters.getInstance(algId.getParameters());
PBKDF2Params func = PBKDF2Params.getInstance(alg.getKeyDerivationFunc().getParameters());
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg.getKeyDerivationFunc().getAlgorithm().getId(), bcProvider);
SecretKey k = keyFact.generateSecret(new PBEKeySpec(password, func.getSalt(), func.getIterationCount().intValue(), SecretKeyUtil.getKeySize(alg.getEncryptionScheme().getAlgorithm())));
Cipher cipher = Cipher.getInstance(alg.getEncryptionScheme().getAlgorithm().getId(), bcProvider);
cipher.init(Cipher.UNWRAP_MODE, k, new IvParameterSpec(ASN1OctetString.getInstance(alg.getEncryptionScheme().getParameters()).getOctets()));
// we pass "" as the key algorithm type as it is unknown at this point
return (PrivateKey) cipher.unwrap(data, "", Cipher.PRIVATE_KEY);
}
} catch (Exception e) {
throw new IOException("exception unwrapping private key - " + e.toString());
}
throw new IOException("exception unwrapping private key - cannot recognise: " + algorithm);
}
Aggregations