use of org.spongycastle.asn1.x509.AlgorithmIdentifier in project android_frameworks_base by DirtyUnicorns.
the class AndroidKeyStoreKeyPairGeneratorSpi method generateSelfSignedCertificateWithFakeSignature.
@SuppressWarnings("deprecation")
private X509Certificate generateSelfSignedCertificateWithFakeSignature(PublicKey publicKey) throws IOException, CertificateParsingException {
V3TBSCertificateGenerator tbsGenerator = new V3TBSCertificateGenerator();
ASN1ObjectIdentifier sigAlgOid;
AlgorithmIdentifier sigAlgId;
byte[] signature;
switch(mKeymasterAlgorithm) {
case KeymasterDefs.KM_ALGORITHM_EC:
sigAlgOid = X9ObjectIdentifiers.ecdsa_with_SHA256;
sigAlgId = new AlgorithmIdentifier(sigAlgOid);
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERInteger(0));
v.add(new DERInteger(0));
signature = new DERSequence().getEncoded();
break;
case KeymasterDefs.KM_ALGORITHM_RSA:
sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE);
signature = new byte[1];
break;
default:
throw new ProviderException("Unsupported key algorithm: " + mKeymasterAlgorithm);
}
try (ASN1InputStream publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded())) {
tbsGenerator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject()));
}
tbsGenerator.setSerialNumber(new ASN1Integer(mSpec.getCertificateSerialNumber()));
X509Principal subject = new X509Principal(mSpec.getCertificateSubject().getEncoded());
tbsGenerator.setSubject(subject);
tbsGenerator.setIssuer(subject);
tbsGenerator.setStartDate(new Time(mSpec.getCertificateNotBefore()));
tbsGenerator.setEndDate(new Time(mSpec.getCertificateNotAfter()));
tbsGenerator.setSignature(sigAlgId);
TBSCertificate tbsCertificate = tbsGenerator.generateTBSCertificate();
ASN1EncodableVector result = new ASN1EncodableVector();
result.add(tbsCertificate);
result.add(sigAlgId);
result.add(new DERBitString(signature));
return new X509CertificateObject(Certificate.getInstance(new DERSequence(result)));
}
use of org.spongycastle.asn1.x509.AlgorithmIdentifier in project robovm by robovm.
the class SubjectPublicKeyInfoTest method test_getPublicKey_WellKnownOid.
public void test_getPublicKey_WellKnownOid() throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
KeyPair pair = kpg.generateKeyPair();
final RSAPublicKey rsaPubKey = (RSAPublicKey) pair.getPublic();
/* Do some fancy footwork to get an ASN.1 SubjectPublicKey for RSA */
final ASN1Sequence rsaPubKeyInfo = new ASN1Sequence(new ASN1Type[] { ASN1Integer.getInstance(), ASN1Integer.getInstance() }) {
@Override
protected void getValues(Object object, Object[] values) {
values[0] = rsaPubKey.getModulus().toByteArray();
values[1] = rsaPubKey.getPublicExponent().toByteArray();
}
};
/* The algorithm ID for RSA encryption */
AlgorithmIdentifier algid = new AlgorithmIdentifier("1.2.840.113549.1.1.1");
SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(algid, rsaPubKeyInfo.encode(null));
PublicKey pubKey = spki.getPublicKey();
assertNotNull(pubKey);
assertTrue(pubKey instanceof RSAPublicKey);
}
use of org.spongycastle.asn1.x509.AlgorithmIdentifier in project robovm by robovm.
the class PKCS12KeyStoreSpi method engineLoad.
public void engineLoad(InputStream stream, char[] password) throws IOException {
if (// just initialising
stream == null) {
return;
}
if (password == null) {
throw new NullPointerException("No password supplied for PKCS#12 KeyStore.");
}
BufferedInputStream bufIn = new BufferedInputStream(stream);
bufIn.mark(10);
int head = bufIn.read();
if (head != 0x30) {
throw new IOException("stream does not represent a PKCS12 key store");
}
bufIn.reset();
ASN1InputStream bIn = new ASN1InputStream(bufIn);
ASN1Sequence obj = (ASN1Sequence) bIn.readObject();
Pfx bag = Pfx.getInstance(obj);
ContentInfo info = bag.getAuthSafe();
Vector chain = new Vector();
boolean unmarkedKey = false;
boolean wrongPKCS12Zero = false;
if (// check the mac code
bag.getMacData() != null) {
MacData mData = bag.getMacData();
DigestInfo dInfo = mData.getMac();
AlgorithmIdentifier algId = dInfo.getAlgorithmId();
byte[] salt = mData.getSalt();
int itCount = mData.getIterationCount().intValue();
byte[] data = ((ASN1OctetString) info.getContent()).getOctets();
try {
byte[] res = calculatePbeMac(algId.getAlgorithm(), salt, itCount, password, false, data);
byte[] dig = dInfo.getDigest();
if (!Arrays.constantTimeAreEqual(res, dig)) {
if (password.length > 0) {
throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file.");
}
// Try with incorrect zero length password
res = calculatePbeMac(algId.getAlgorithm(), salt, itCount, password, true, data);
if (!Arrays.constantTimeAreEqual(res, dig)) {
throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file.");
}
wrongPKCS12Zero = true;
}
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException("error constructing MAC: " + e.toString());
}
}
keys = new IgnoresCaseHashtable();
localIds = new Hashtable();
if (info.getContentType().equals(data)) {
bIn = new ASN1InputStream(((ASN1OctetString) info.getContent()).getOctets());
AuthenticatedSafe authSafe = AuthenticatedSafe.getInstance(bIn.readObject());
ContentInfo[] c = authSafe.getContentInfo();
for (int i = 0; i != c.length; i++) {
if (c[i].getContentType().equals(data)) {
ASN1InputStream dIn = new ASN1InputStream(((ASN1OctetString) c[i].getContent()).getOctets());
ASN1Sequence seq = (ASN1Sequence) dIn.readObject();
for (int j = 0; j != seq.size(); j++) {
SafeBag b = SafeBag.getInstance(seq.getObjectAt(j));
if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue());
PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero);
//
// set the attributes on the key
//
PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
String alias = null;
ASN1OctetString localId = null;
if (b.getBagAttributes() != null) {
Enumeration e = b.getBagAttributes().getObjects();
while (e.hasMoreElements()) {
ASN1Sequence sq = (ASN1Sequence) e.nextElement();
ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
ASN1Primitive attr = null;
if (attrSet.size() > 0) {
attr = (ASN1Primitive) attrSet.getObjectAt(0);
ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
if (existing != null) {
// OK, but the value has to be the same
if (!existing.toASN1Primitive().equals(attr)) {
throw new IOException("attempt to add existing attribute with different value");
}
} else {
bagAttr.setBagAttribute(aOid, attr);
}
}
if (aOid.equals(pkcs_9_at_friendlyName)) {
alias = ((DERBMPString) attr).getString();
keys.put(alias, privKey);
} else if (aOid.equals(pkcs_9_at_localKeyId)) {
localId = (ASN1OctetString) attr;
}
}
}
if (localId != null) {
String name = new String(Hex.encode(localId.getOctets()));
if (alias == null) {
keys.put(name, privKey);
} else {
localIds.put(alias, name);
}
} else {
unmarkedKey = true;
keys.put("unmarked", privKey);
}
} else if (b.getBagId().equals(certBag)) {
chain.addElement(b);
} else {
System.out.println("extra in data " + b.getBagId());
System.out.println(ASN1Dump.dumpAsString(b));
}
}
} else if (c[i].getContentType().equals(encryptedData)) {
EncryptedData d = EncryptedData.getInstance(c[i].getContent());
byte[] octets = cryptData(false, d.getEncryptionAlgorithm(), password, wrongPKCS12Zero, d.getContent().getOctets());
ASN1Sequence seq = (ASN1Sequence) ASN1Primitive.fromByteArray(octets);
for (int j = 0; j != seq.size(); j++) {
SafeBag b = SafeBag.getInstance(seq.getObjectAt(j));
if (b.getBagId().equals(certBag)) {
chain.addElement(b);
} else if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue());
PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero);
//
// set the attributes on the key
//
PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
String alias = null;
ASN1OctetString localId = null;
Enumeration e = b.getBagAttributes().getObjects();
while (e.hasMoreElements()) {
ASN1Sequence sq = (ASN1Sequence) e.nextElement();
ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
ASN1Primitive attr = null;
if (attrSet.size() > 0) {
attr = (ASN1Primitive) attrSet.getObjectAt(0);
ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
if (existing != null) {
// OK, but the value has to be the same
if (!existing.toASN1Primitive().equals(attr)) {
throw new IOException("attempt to add existing attribute with different value");
}
} else {
bagAttr.setBagAttribute(aOid, attr);
}
}
if (aOid.equals(pkcs_9_at_friendlyName)) {
alias = ((DERBMPString) attr).getString();
keys.put(alias, privKey);
} else if (aOid.equals(pkcs_9_at_localKeyId)) {
localId = (ASN1OctetString) attr;
}
}
String name = new String(Hex.encode(localId.getOctets()));
if (alias == null) {
keys.put(name, privKey);
} else {
localIds.put(alias, name);
}
} else if (b.getBagId().equals(keyBag)) {
org.bouncycastle.asn1.pkcs.PrivateKeyInfo kInfo = org.bouncycastle.asn1.pkcs.PrivateKeyInfo.getInstance(b.getBagValue());
PrivateKey privKey = BouncyCastleProvider.getPrivateKey(kInfo);
//
// set the attributes on the key
//
PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
String alias = null;
ASN1OctetString localId = null;
Enumeration e = b.getBagAttributes().getObjects();
while (e.hasMoreElements()) {
ASN1Sequence sq = (ASN1Sequence) e.nextElement();
ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
ASN1Primitive attr = null;
if (attrSet.size() > 0) {
attr = (ASN1Primitive) attrSet.getObjectAt(0);
ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
if (existing != null) {
// OK, but the value has to be the same
if (!existing.toASN1Primitive().equals(attr)) {
throw new IOException("attempt to add existing attribute with different value");
}
} else {
bagAttr.setBagAttribute(aOid, attr);
}
}
if (aOid.equals(pkcs_9_at_friendlyName)) {
alias = ((DERBMPString) attr).getString();
keys.put(alias, privKey);
} else if (aOid.equals(pkcs_9_at_localKeyId)) {
localId = (ASN1OctetString) attr;
}
}
String name = new String(Hex.encode(localId.getOctets()));
if (alias == null) {
keys.put(name, privKey);
} else {
localIds.put(alias, name);
}
} else {
System.out.println("extra in encryptedData " + b.getBagId());
System.out.println(ASN1Dump.dumpAsString(b));
}
}
} else {
System.out.println("extra " + c[i].getContentType().getId());
System.out.println("extra " + ASN1Dump.dumpAsString(c[i].getContent()));
}
}
}
certs = new IgnoresCaseHashtable();
chainCerts = new Hashtable();
keyCerts = new Hashtable();
for (int i = 0; i != chain.size(); i++) {
SafeBag b = (SafeBag) chain.elementAt(i);
CertBag cb = CertBag.getInstance(b.getBagValue());
if (!cb.getCertId().equals(x509Certificate)) {
throw new RuntimeException("Unsupported certificate type: " + cb.getCertId());
}
Certificate cert;
try {
ByteArrayInputStream cIn = new ByteArrayInputStream(((ASN1OctetString) cb.getCertValue()).getOctets());
cert = certFact.generateCertificate(cIn);
} catch (Exception e) {
throw new RuntimeException(e.toString());
}
//
// set the attributes
//
ASN1OctetString localId = null;
String alias = null;
if (b.getBagAttributes() != null) {
Enumeration e = b.getBagAttributes().getObjects();
while (e.hasMoreElements()) {
ASN1Sequence sq = (ASN1Sequence) e.nextElement();
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
ASN1Primitive attr = (ASN1Primitive) ((ASN1Set) sq.getObjectAt(1)).getObjectAt(0);
PKCS12BagAttributeCarrier bagAttr = null;
if (cert instanceof PKCS12BagAttributeCarrier) {
bagAttr = (PKCS12BagAttributeCarrier) cert;
ASN1Encodable existing = bagAttr.getBagAttribute(oid);
if (existing != null) {
// OK, but the value has to be the same
if (!existing.toASN1Primitive().equals(attr)) {
throw new IOException("attempt to add existing attribute with different value");
}
} else {
bagAttr.setBagAttribute(oid, attr);
}
}
if (oid.equals(pkcs_9_at_friendlyName)) {
alias = ((DERBMPString) attr).getString();
} else if (oid.equals(pkcs_9_at_localKeyId)) {
localId = (ASN1OctetString) attr;
}
}
}
chainCerts.put(new CertId(cert.getPublicKey()), cert);
if (unmarkedKey) {
if (keyCerts.isEmpty()) {
String name = new String(Hex.encode(createSubjectKeyId(cert.getPublicKey()).getKeyIdentifier()));
keyCerts.put(name, cert);
keys.put(name, keys.remove("unmarked"));
}
} else {
//
if (localId != null) {
String name = new String(Hex.encode(localId.getOctets()));
keyCerts.put(name, cert);
}
if (alias != null) {
certs.put(alias, cert);
}
}
}
}
use of org.spongycastle.asn1.x509.AlgorithmIdentifier in project robovm by robovm.
the class PKCS10CertificationRequest method getPublicKey.
public PublicKey getPublicKey(String provider) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
SubjectPublicKeyInfo subjectPKInfo = reqInfo.getSubjectPublicKeyInfo();
try {
X509EncodedKeySpec xspec = new X509EncodedKeySpec(new DERBitString(subjectPKInfo).getBytes());
AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
try {
if (provider == null) {
return KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
} else {
return KeyFactory.getInstance(keyAlg.getAlgorithm().getId(), provider).generatePublic(xspec);
}
} catch (NoSuchAlgorithmException e) {
//
if (keyAlgorithms.get(keyAlg.getObjectId()) != null) {
String keyAlgorithm = (String) keyAlgorithms.get(keyAlg.getObjectId());
if (provider == null) {
return KeyFactory.getInstance(keyAlgorithm).generatePublic(xspec);
} else {
return KeyFactory.getInstance(keyAlgorithm, provider).generatePublic(xspec);
}
}
throw e;
}
} catch (InvalidKeySpecException e) {
throw new InvalidKeyException("error decoding public key");
} catch (IOException e) {
throw new InvalidKeyException("error decoding public key");
}
}
use of org.spongycastle.asn1.x509.AlgorithmIdentifier in project robovm by robovm.
the class JcaContentVerifierProviderBuilder method build.
public ContentVerifierProvider build(final PublicKey publicKey) throws OperatorCreationException {
return new ContentVerifierProvider() {
public boolean hasAssociatedCertificate() {
return false;
}
public X509CertificateHolder getAssociatedCertificate() {
return null;
}
public ContentVerifier get(AlgorithmIdentifier algorithm) throws OperatorCreationException {
SignatureOutputStream stream = createSignatureStream(algorithm, publicKey);
Signature rawSig = createRawSig(algorithm, publicKey);
if (rawSig != null) {
return new RawSigVerifier(algorithm, stream, rawSig);
} else {
return new SigVerifier(algorithm, stream);
}
}
};
}
Aggregations