use of com.mindbright.asn1.ASN1Integer in project keystore-explorer by kaikramer.
the class OpenSslPvkUtil method getEncryptionType.
/**
* Detect if a OpenSSL private key is encrypted or not.
*
* @param is
* Input stream containing OpenSSL private key
* @return Encryption type or null if not a valid OpenSSL private key
* @throws IOException
* If an I/O problem occurred
*/
public static EncryptionType getEncryptionType(InputStream is) throws IOException {
byte[] openSsl = ReadUtil.readFully(is);
// In PEM format?
PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(openSsl));
if (pemInfo != null) {
String pemType = pemInfo.getType();
// PEM type of OpenSSL?
if (OPENSSL_RSA_PVK_PEM_TYPE.equals(pemType) || OPENSSL_DSA_PVK_PEM_TYPE.equals(pemType) || OPENSSL_EC_PVK_PEM_TYPE.equals(pemType)) {
// Encrypted? It is if PEM contains appropriate header attributes/values
PemAttributes pemAttributes = pemInfo.getAttributes();
if ((pemAttributes != null) && (pemAttributes.get(PROC_TYPE_ATTR_NAME) != null) && (pemAttributes.get(PROC_TYPE_ATTR_NAME).getValue().equals(PROC_TYPE_ATTR_VALUE)) && (pemAttributes.get(DEK_INFO_ATTR_NAME) != null)) {
return ENCRYPTED;
} else {
return UNENCRYPTED;
}
}
}
// In ASN.1 format?
try {
// If OpenSSL will be a sequence of 9 (RSA) or 6 (DSA) integers or 2-4 mixed elements (EC)
ASN1Primitive key = ASN1Primitive.fromByteArray(openSsl);
if (key instanceof ASN1Sequence) {
ASN1Sequence seq = (ASN1Sequence) key;
// }
if ((seq.size() >= 2) && (seq.size() <= 4) && seq.getObjectAt(0) instanceof ASN1Integer) {
BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
if (version.equals(VERSION_EC)) {
if (seq.getObjectAt(1) instanceof ASN1OctetString) {
// ASN.1 OpenSSL is always unencrypted
return UNENCRYPTED;
} else {
// Not OpenSSL
return null;
}
}
}
for (int i = 0; i < seq.size(); i++) {
if (!(seq.getObjectAt(i) instanceof ASN1Integer)) {
// Not OpenSSL
return null;
}
}
if ((seq.size() == 9) || (seq.size() == 6)) {
// ASN.1 OpenSSL is always unencrypted
return UNENCRYPTED;
}
}
} catch (IOException ex) {
// Not an OpenSSL file
return null;
}
// Not an OpenSSL file
return null;
}
use of com.mindbright.asn1.ASN1Integer in project keystore-explorer by kaikramer.
the class Pkcs8Util method getEncryptionType.
/**
* Detect if a PKCS #8 private key is encrypted or not.
*
* @param is
* Input stream containing PKCS #8 private key
* @return Encryption type or null if not a valid PKCS #8 private key
* @throws IOException
* If an I/O problem occurred
*/
public static EncryptionType getEncryptionType(InputStream is) throws IOException {
byte[] pkcs8 = ReadUtil.readFully(is);
PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(pkcs8));
// PEM encoded?
if (pemInfo != null) {
String pemType = pemInfo.getType();
// Encrypted in pem format?
if (pemType.equals(Pkcs8Util.PKCS8_ENC_PVK_PEM_TYPE)) {
return ENCRYPTED;
} else // Unencrypted in pem format?
if (pemType.equals(Pkcs8Util.PKCS8_UNENC_PVK_PEM_TYPE)) {
return UNENCRYPTED;
}
}
// In ASN.1 format?
try {
// Read in an ASN.1 and check structure against the following
ASN1Primitive key = ASN1Primitive.fromByteArray(pkcs8);
if (key instanceof ASN1Sequence) {
ASN1Sequence sequence = (ASN1Sequence) key;
// May be unencrypted
if ((sequence.size() == 3) || (sequence.size() == 4)) {
// @formatter:off
/*
* Unencrypted PKCS #8 Private Key:
*
* PrivateKeyInfo ::= ASN1Sequence { version Version,
* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
* privateKey PrivateKey, attributes [0] IMPLICIT Attributes
* OPTIONAL }
*
* Version ::= ASN1Integer PrivateKeyAlgorithmIdentifier ::=
* AlgorithmIdentifier PrivateKey ::= OCTET STRING
* Attributes ::= SET OF Attribute
*/
// @formatter:on
Object obj1 = sequence.getObjectAt(0);
Object obj2 = sequence.getObjectAt(1);
Object obj3 = sequence.getObjectAt(2);
if (!(obj1 instanceof ASN1Integer)) {
return null;
}
ASN1Integer version = (ASN1Integer) obj1;
if (!version.getValue().equals(BigInteger.ZERO)) {
return null;
}
if (!(obj2 instanceof ASN1Sequence)) {
return null;
}
if (!sequenceIsAlgorithmIdentifier((ASN1Sequence) obj2)) {
return null;
}
if (!(obj3 instanceof ASN1OctetString)) {
return null;
}
return UNENCRYPTED;
} else // May be encrypted
if (sequence.size() == 2) {
// @formatter:off
/*
* Encrypted PKCS #8 Private Key:
*
* EncryptedPrivateKeyInfo ::= ASN1Sequence {
* encryptionAlgorithm EncryptionAlgorithmIdentifier,
* encryptedData EncryptedData }
*
* EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
* EncryptedData ::= OCTET STRING
*/
// @formatter:on
Object obj1 = sequence.getObjectAt(0);
Object obj2 = sequence.getObjectAt(1);
if (!(obj1 instanceof ASN1Sequence)) {
return null;
}
if (!sequenceIsAlgorithmIdentifier((ASN1Sequence) obj1)) {
return null;
}
if (!(obj2 instanceof ASN1OctetString)) {
return null;
}
return ENCRYPTED;
}
}
} catch (Exception ex) {
// Structure not as expected for PKCS #8
return null;
}
return null;
}
use of com.mindbright.asn1.ASN1Integer in project keystore-explorer by kaikramer.
the class CryptoFileUtil method detectKeyStoreType.
/**
* Detect the KeyStore type contained in the supplied file.
*
* @param is
* Input stream to detect type for
* @return KeyStore type or null if none matched
* @throws IOException
* If an I/O problem occurred
*/
public static KeyStoreType detectKeyStoreType(InputStream is) throws IOException {
byte[] contents = ReadUtil.readFully(is);
try (DataInputStream dis = new DataInputStream(new ByteArrayInputStream(contents))) {
// If less than 4 bytes are available it isn't a KeyStore
if (dis.available() < 4) {
return null;
}
// Read first integer (4 bytes)
int i1 = dis.readInt();
// Test for JKS - starts with appropriate magic number
if (i1 == JKS_MAGIC_NUMBER) {
return JKS;
}
// Test for JCEKS - starts with appropriate magic number
if (i1 == JCEKS_MAGIC_NUMBER) {
return JCEKS;
}
// Both start with a version number of 0, 1 or 2
if ((i1 == 0) || (i1 == 1) || (i1 == 2)) {
if (contents.length < 26) {
// Insufficient bytes to be BKS or UBER
return null;
}
// Skip to 21st from last byte (file length minus 21 and the 4 bytes already read)
dis.skip(contents.length - 25);
// Read what may be the null byte
if (dis.readByte() == 0) {
// Found null byte - BKS/BKS-V1
if (i1 == 1) {
return BKS_V1;
} else {
return BKS;
}
} else {
// No null byte - UBER
return UBER;
}
}
}
// @formatter:off
/*
* Test for PKCS #12. ASN.1 should look like this:
*
* PFX ::= ASN1Sequence { version ASN1Integer {v3(3)}(v3,...), authSafe
* ContentInfo, macData MacData OPTIONAL
*/
// @formatter:on
ASN1Primitive pfx = null;
try {
pfx = ASN1Primitive.fromByteArray(contents);
} catch (IOException e) {
// if it cannot be parsed as ASN1, it is certainly not a pfx key store
return null;
}
// Is a sequence...
if ((pfx != null) && (pfx instanceof ASN1Sequence)) {
// Has two or three components...
ASN1Sequence sequence = (ASN1Sequence) pfx;
if ((sequence.size() == 2) || (sequence.size() == 3)) {
// ...the first of which is a version of 3
ASN1Encodable firstComponent = sequence.getObjectAt(0);
if (firstComponent instanceof ASN1Integer) {
ASN1Integer version = (ASN1Integer) firstComponent;
if (version.getValue().intValue() == 3) {
return PKCS12;
}
}
}
}
// KeyStore type not recognised
return null;
}
use of com.mindbright.asn1.ASN1Integer in project xipki by xipki.
the class XmlX509CertprofileUtil method buildPolicyConstrains.
// method buildGeneralSubtree
public static ASN1Sequence buildPolicyConstrains(PolicyConstraints type) throws CertprofileException {
ParamUtil.requireNonNull("type", type);
Integer requireExplicitPolicy = type.getRequireExplicitPolicy();
if (requireExplicitPolicy != null && requireExplicitPolicy < 0) {
throw new CertprofileException("negative requireExplicitPolicy is not allowed: " + requireExplicitPolicy);
}
Integer inhibitPolicyMapping = type.getInhibitPolicyMapping();
if (inhibitPolicyMapping != null && inhibitPolicyMapping < 0) {
throw new CertprofileException("negative inhibitPolicyMapping is not allowed: " + inhibitPolicyMapping);
}
if (requireExplicitPolicy == null && inhibitPolicyMapping == null) {
return null;
}
final boolean explicit = false;
ASN1EncodableVector vec = new ASN1EncodableVector();
if (requireExplicitPolicy != null) {
vec.add(new DERTaggedObject(explicit, 0, new ASN1Integer(BigInteger.valueOf(requireExplicitPolicy))));
}
if (inhibitPolicyMapping != null) {
vec.add(new DERTaggedObject(explicit, 1, new ASN1Integer(BigInteger.valueOf(inhibitPolicyMapping))));
}
return new DERSequence(vec);
}
use of com.mindbright.asn1.ASN1Integer in project xipki by xipki.
the class BaseX509Certprofile method checkPublicKey.
@Override
public SubjectPublicKeyInfo checkPublicKey(SubjectPublicKeyInfo publicKey) throws BadCertTemplateException {
ParamUtil.requireNonNull("publicKey", publicKey);
Map<ASN1ObjectIdentifier, KeyParametersOption> keyAlgorithms = getKeyAlgorithms();
if (CollectionUtil.isEmpty(keyAlgorithms)) {
return publicKey;
}
ASN1ObjectIdentifier keyType = publicKey.getAlgorithm().getAlgorithm();
if (!keyAlgorithms.containsKey(keyType)) {
throw new BadCertTemplateException("key type " + keyType.getId() + " is not permitted");
}
KeyParametersOption keyParamsOption = keyAlgorithms.get(keyType);
if (keyParamsOption instanceof AllowAllParametersOption) {
return publicKey;
} else if (keyParamsOption instanceof ECParamatersOption) {
ECParamatersOption ecOption = (ECParamatersOption) keyParamsOption;
// parameters
ASN1Encodable algParam = publicKey.getAlgorithm().getParameters();
ASN1ObjectIdentifier curveOid;
if (algParam instanceof ASN1ObjectIdentifier) {
curveOid = (ASN1ObjectIdentifier) algParam;
if (!ecOption.allowsCurve(curveOid)) {
throw new BadCertTemplateException(String.format("EC curve %s (OID: %s) is not allowed", AlgorithmUtil.getCurveName(curveOid), curveOid.getId()));
}
} else {
throw new BadCertTemplateException("only namedCurve EC public key is supported");
}
// point encoding
if (ecOption.pointEncodings() != null) {
byte[] keyData = publicKey.getPublicKeyData().getBytes();
if (keyData.length < 1) {
throw new BadCertTemplateException("invalid publicKeyData");
}
byte pointEncoding = keyData[0];
if (!ecOption.pointEncodings().contains(pointEncoding)) {
throw new BadCertTemplateException(String.format("not accepted EC point encoding '%s'", pointEncoding));
}
}
byte[] keyData = publicKey.getPublicKeyData().getBytes();
try {
checkEcSubjectPublicKeyInfo(curveOid, keyData);
} catch (BadCertTemplateException ex) {
throw ex;
} catch (Exception ex) {
LogUtil.warn(LOG, ex, "checkEcSubjectPublicKeyInfo");
throw new BadCertTemplateException(String.format("invalid public key: %s", ex.getMessage()));
}
return publicKey;
} else if (keyParamsOption instanceof RSAParametersOption) {
RSAParametersOption rsaOption = (RSAParametersOption) keyParamsOption;
ASN1Integer modulus;
try {
ASN1Sequence seq = ASN1Sequence.getInstance(publicKey.getPublicKeyData().getBytes());
modulus = ASN1Integer.getInstance(seq.getObjectAt(0));
} catch (IllegalArgumentException ex) {
throw new BadCertTemplateException("invalid publicKeyData");
}
int modulusLength = modulus.getPositiveValue().bitLength();
if ((rsaOption.allowsModulusLength(modulusLength))) {
return publicKey;
}
} else if (keyParamsOption instanceof DSAParametersOption) {
DSAParametersOption dsaOption = (DSAParametersOption) keyParamsOption;
ASN1Encodable params = publicKey.getAlgorithm().getParameters();
if (params == null) {
throw new BadCertTemplateException("null Dss-Parms is not permitted");
}
int plength;
int qlength;
try {
ASN1Sequence seq = ASN1Sequence.getInstance(params);
ASN1Integer rsaP = ASN1Integer.getInstance(seq.getObjectAt(0));
ASN1Integer rsaQ = ASN1Integer.getInstance(seq.getObjectAt(1));
plength = rsaP.getPositiveValue().bitLength();
qlength = rsaQ.getPositiveValue().bitLength();
} catch (IllegalArgumentException | ArrayIndexOutOfBoundsException ex) {
throw new BadCertTemplateException("illegal Dss-Parms");
}
boolean match = dsaOption.allowsPlength(plength);
if (match) {
match = dsaOption.allowsQlength(qlength);
}
if (match) {
return publicKey;
}
} else {
throw new RuntimeException(String.format("should not reach here, unknown KeyParametersOption %s", keyParamsOption));
}
throw new BadCertTemplateException("the given publicKey is not permitted");
}
Aggregations