use of com.mindbright.asn1.ASN1Integer in project android_frameworks_base by crdroidandroid.
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 com.mindbright.asn1.ASN1Integer in project android_frameworks_base by crdroidandroid.
the class ESTHandler method unpackPkcs7.
private static List<X509Certificate> unpackPkcs7(ByteBuffer pkcs7) throws IOException, GeneralSecurityException {
Collection<Asn1Object> pkcs7Content = Asn1Decoder.decode(pkcs7);
if (pkcs7Content.size() != 1) {
throw new IOException("Unexpected pkcs 7 container: " + pkcs7Content.size());
}
Asn1Object data = pkcs7Content.iterator().next();
if (!data.isConstructed() || !data.matches(sSEQUENCE)) {
throw new IOException("Expected SEQ OF, got " + data.toSimpleString());
} else if (data.getChildren().size() != 2) {
throw new IOException("Expected content info to have two children, got " + data.getChildren().size());
}
Iterator<Asn1Object> children = data.getChildren().iterator();
Asn1Object contentType = children.next();
if (!contentType.equals(Asn1Oid.PKCS7SignedData)) {
throw new IOException("Content not PKCS7 signed data");
}
Asn1Object content = children.next();
if (!content.isConstructed() || !content.matches(sCTXT0)) {
throw new IOException("Expected [CONTEXT 0] with one child, got " + content.toSimpleString() + ", " + content.getChildren().size());
}
Asn1Object signedData = content.getChildren().iterator().next();
Map<Integer, Asn1Object> itemMap = new HashMap<>();
for (Asn1Object item : signedData.getChildren()) {
if (itemMap.put(item.getTag(), item) != null && item.getTag() != Asn1Decoder.TAG_SET) {
throw new IOException("Duplicate item in SignedData: " + item.toSimpleString());
}
}
Asn1Object versionObject = itemMap.get(Asn1Decoder.TAG_INTEGER);
if (versionObject == null || !(versionObject instanceof Asn1Integer)) {
throw new IOException("Bad or missing PKCS7 version: " + versionObject);
}
int pkcs7version = (int) ((Asn1Integer) versionObject).getValue();
Asn1Object innerContentInfo = itemMap.get(Asn1Decoder.TAG_SEQ);
if (innerContentInfo == null || !innerContentInfo.isConstructed() || !innerContentInfo.matches(sSEQUENCE) || innerContentInfo.getChildren().size() != 1) {
throw new IOException("Bad or missing PKCS7 contentInfo");
}
Asn1Object contentID = innerContentInfo.getChildren().iterator().next();
if (pkcs7version == PKCS7DataVersion && !contentID.equals(Asn1Oid.PKCS7Data) || pkcs7version == PKCS7SignedDataVersion && !contentID.equals(Asn1Oid.PKCS7SignedData)) {
throw new IOException("Inner PKCS7 content (" + contentID + ") not expected for version " + pkcs7version);
}
Asn1Object certWrapper = itemMap.get(0);
if (certWrapper == null || !certWrapper.isConstructed() || !certWrapper.matches(sCTXT0)) {
throw new IOException("Expected [CONTEXT 0], got: " + certWrapper);
}
List<X509Certificate> certList = new ArrayList<>(certWrapper.getChildren().size());
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
for (Asn1Object certObject : certWrapper.getChildren()) {
ByteBuffer certOctets = ((Asn1Constructed) certObject).getEncoding();
if (certOctets == null) {
throw new IOException("No cert payload in: " + certObject);
}
byte[] certBytes = new byte[certOctets.remaining()];
certOctets.get(certBytes);
certList.add((X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certBytes)));
}
return certList;
}
use of com.mindbright.asn1.ASN1Integer in project android_frameworks_base by AOSPA.
the class ESTHandler method unpackPkcs7.
private static List<X509Certificate> unpackPkcs7(ByteBuffer pkcs7) throws IOException, GeneralSecurityException {
Collection<Asn1Object> pkcs7Content = Asn1Decoder.decode(pkcs7);
if (pkcs7Content.size() != 1) {
throw new IOException("Unexpected pkcs 7 container: " + pkcs7Content.size());
}
Asn1Object data = pkcs7Content.iterator().next();
if (!data.isConstructed() || !data.matches(sSEQUENCE)) {
throw new IOException("Expected SEQ OF, got " + data.toSimpleString());
} else if (data.getChildren().size() != 2) {
throw new IOException("Expected content info to have two children, got " + data.getChildren().size());
}
Iterator<Asn1Object> children = data.getChildren().iterator();
Asn1Object contentType = children.next();
if (!contentType.equals(Asn1Oid.PKCS7SignedData)) {
throw new IOException("Content not PKCS7 signed data");
}
Asn1Object content = children.next();
if (!content.isConstructed() || !content.matches(sCTXT0)) {
throw new IOException("Expected [CONTEXT 0] with one child, got " + content.toSimpleString() + ", " + content.getChildren().size());
}
Asn1Object signedData = content.getChildren().iterator().next();
Map<Integer, Asn1Object> itemMap = new HashMap<>();
for (Asn1Object item : signedData.getChildren()) {
if (itemMap.put(item.getTag(), item) != null && item.getTag() != Asn1Decoder.TAG_SET) {
throw new IOException("Duplicate item in SignedData: " + item.toSimpleString());
}
}
Asn1Object versionObject = itemMap.get(Asn1Decoder.TAG_INTEGER);
if (versionObject == null || !(versionObject instanceof Asn1Integer)) {
throw new IOException("Bad or missing PKCS7 version: " + versionObject);
}
int pkcs7version = (int) ((Asn1Integer) versionObject).getValue();
Asn1Object innerContentInfo = itemMap.get(Asn1Decoder.TAG_SEQ);
if (innerContentInfo == null || !innerContentInfo.isConstructed() || !innerContentInfo.matches(sSEQUENCE) || innerContentInfo.getChildren().size() != 1) {
throw new IOException("Bad or missing PKCS7 contentInfo");
}
Asn1Object contentID = innerContentInfo.getChildren().iterator().next();
if (pkcs7version == PKCS7DataVersion && !contentID.equals(Asn1Oid.PKCS7Data) || pkcs7version == PKCS7SignedDataVersion && !contentID.equals(Asn1Oid.PKCS7SignedData)) {
throw new IOException("Inner PKCS7 content (" + contentID + ") not expected for version " + pkcs7version);
}
Asn1Object certWrapper = itemMap.get(0);
if (certWrapper == null || !certWrapper.isConstructed() || !certWrapper.matches(sCTXT0)) {
throw new IOException("Expected [CONTEXT 0], got: " + certWrapper);
}
List<X509Certificate> certList = new ArrayList<>(certWrapper.getChildren().size());
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
for (Asn1Object certObject : certWrapper.getChildren()) {
ByteBuffer certOctets = ((Asn1Constructed) certObject).getEncoding();
if (certOctets == null) {
throw new IOException("No cert payload in: " + certObject);
}
byte[] certBytes = new byte[certOctets.remaining()];
certOctets.get(certBytes);
certList.add((X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certBytes)));
}
return certList;
}
use of com.mindbright.asn1.ASN1Integer in project web3sdk by FISCO-BCOS.
the class SignTest method testGmSignVerify.
@Test
public void testGmSignVerify() throws IOException {
byte[] sourceData = Hex.decode("434477813974bf58f94bcf760833c2b40f77a5fc360485b0b9ed1bd9682edb45");
String publicKey = "e8c670380cb220095268f40221fc748fa6ac39d6e930e63c30da68bad97f885da6e8c9ad722c3683ab859393220d1431eb1818ed44a942efb07b261a0fc769e7";
String sign = "09628650676000c8d18bf43db68e7f66dfaed230d87e6391c29eb594b7b9cc3c8d370dbd29ce62bbcf3506adb57f041d8646ae4f70a26ea5179418e738fd4372e8c670380cb220095268f40221fc748fa6ac39d6e930e63c30da68bad97f885da6e8c9ad722c3683ab859393220d1431eb1818ed44a942efb07b261a0fc769e7";
byte[] signatureBytes = Numeric.hexStringToByteArray("0x" + sign);
ASN1Integer d_r = new ASN1Integer(new BigInteger(1, Arrays.copyOfRange(signatureBytes, 0, 32)));
ASN1Integer d_s = new ASN1Integer(new BigInteger(1, Arrays.copyOfRange(signatureBytes, 32, 64)));
ASN1EncodableVector v2 = new ASN1EncodableVector();
v2.add(d_r);
v2.add(d_s);
DERSequence der = new DERSequence(v2);
boolean b = SM2Algorithm.verify(sourceData, der.getEncoded(), publicKey.substring(0, 64), publicKey.substring(64, 128));
assertTrue("Test sm2 verify", b);
}
use of com.mindbright.asn1.ASN1Integer in project keystore-explorer by kaikramer.
the class OpenSslPvkUtil method load.
/**
* Load an unencrypted OpenSSL private key from the stream. The encoding of
* the private key may be PEM or DER.
*
* @param is
* Stream to load the unencrypted private key from
* @return The private key
* @throws PrivateKeyEncryptedException
* If private key is encrypted
* @throws CryptoException
* Problem encountered while loading the private key
* @throws IOException
* An I/O error occurred
*/
public static PrivateKey load(InputStream is) throws CryptoException, IOException {
byte[] streamContents = ReadUtil.readFully(is);
EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));
if (encType == null) {
throw new CryptoException(res.getString("NotValidOpenSsl.exception.message"));
}
if (encType == ENCRYPTED) {
throw new PrivateKeyEncryptedException(res.getString("OpenSslIsEncrypted.exception.message"));
}
// Check if stream is PEM encoded
PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));
if (pemInfo != null) {
// It is - get DER from PEM
streamContents = pemInfo.getContent();
}
try {
// Read OpenSSL DER structure
ASN1InputStream asn1InputStream = new ASN1InputStream(streamContents);
ASN1Primitive openSsl = asn1InputStream.readObject();
asn1InputStream.close();
if (openSsl instanceof ASN1Sequence) {
ASN1Sequence seq = (ASN1Sequence) openSsl;
if (seq.size() == 9) {
// RSA private key
BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
BigInteger modulus = ((ASN1Integer) seq.getObjectAt(1)).getValue();
BigInteger publicExponent = ((ASN1Integer) seq.getObjectAt(2)).getValue();
BigInteger privateExponent = ((ASN1Integer) seq.getObjectAt(3)).getValue();
BigInteger primeP = ((ASN1Integer) seq.getObjectAt(4)).getValue();
BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(5)).getValue();
BigInteger primeExponentP = ((ASN1Integer) seq.getObjectAt(6)).getValue();
BigInteger primeExponenetQ = ((ASN1Integer) seq.getObjectAt(7)).getValue();
BigInteger crtCoefficient = ((ASN1Integer) seq.getObjectAt(8)).getValue();
if (!version.equals(VERSION)) {
throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
}
RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponenetQ, crtCoefficient);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(rsaPrivateCrtKeySpec);
} else if (seq.size() == 6) {
// DSA private key
BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
BigInteger primeModulusP = ((ASN1Integer) seq.getObjectAt(1)).getValue();
BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(2)).getValue();
BigInteger generatorG = ((ASN1Integer) seq.getObjectAt(3)).getValue();
// publicExponentY not req for pvk: sequence.getObjectAt(4);
BigInteger secretExponentX = ((ASN1Integer) seq.getObjectAt(5)).getValue();
if (!version.equals(VERSION)) {
throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
}
DSAPrivateKeySpec dsaPrivateKeySpec = new DSAPrivateKeySpec(secretExponentX, primeModulusP, primeQ, generatorG);
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
return keyFactory.generatePrivate(dsaPrivateKeySpec);
} else if (seq.size() >= 2) {
// EC private key (RFC 5915)
org.bouncycastle.asn1.sec.ECPrivateKey pKey = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(seq);
AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParameters());
PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey);
return new JcaPEMKeyConverter().getPrivateKey(privInfo);
} else {
throw new CryptoException(MessageFormat.format(res.getString("OpenSslSequenceIncorrectSize.exception.message"), "" + seq.size()));
}
} else {
throw new CryptoException(res.getString("OpenSslSequenceNotFound.exception.message"));
}
} catch (Exception ex) {
throw new CryptoException(res.getString("NoLoadOpenSslPrivateKey.exception.message"), ex);
}
}
Aggregations