use of com.google.protobuf2.Any in project jss by dogtagpki.
the class PKCS12Util method getKeyInfo.
/**
* Loads key bags (for IMPORT and other operations on existing
* PKCS #12 files). Does not decrypt EncryptedPrivateKeyInfo
* values, but stores them in PKCS12KeyInfo objects for possible
* later use.
*/
public PKCS12KeyInfo getKeyInfo(SafeBag bag, Password password) throws Exception {
PKCS12KeyInfo keyInfo = new PKCS12KeyInfo(bag.getBagContent().getEncoded());
// get key attributes
SET bagAttrs = bag.getBagAttributes();
for (int i = 0; bagAttrs != null && i < bagAttrs.size(); i++) {
Attribute attr = (Attribute) bagAttrs.elementAt(i);
OBJECT_IDENTIFIER oid = attr.getType();
if (oid.equals(SafeBag.FRIENDLY_NAME)) {
SET values = attr.getValues();
ANY value = (ANY) values.elementAt(0);
ByteArrayInputStream bis = new ByteArrayInputStream(value.getEncoded());
BMPString friendlyName = (BMPString) new BMPString.Template().decode(bis);
keyInfo.setFriendlyName(friendlyName.toString());
logger.debug(" Friendly name: " + keyInfo.getFriendlyName());
} else if (oid.equals(SafeBag.LOCAL_KEY_ID)) {
SET values = attr.getValues();
ANY value = (ANY) values.elementAt(0);
ByteArrayInputStream bis = new ByteArrayInputStream(value.getEncoded());
OCTET_STRING keyIdAsn1 = (OCTET_STRING) new OCTET_STRING.Template().decode(bis);
byte[] keyID = keyIdAsn1.toByteArray();
keyInfo.setID(keyID);
} else {
logger.warn(" " + oid + ": " + attr.getValues());
}
}
return keyInfo;
}
use of com.google.protobuf2.Any in project jss by dogtagpki.
the class SignerInfo method verifyWithAuthenticatedAttributes.
/**
* Verifies a SignerInfo with authenticated attributes. If authenticated
* attributes are present, then two particular attributes must
* be present: <ul>
* <li>PKCS #9 Content-Type, the type of content that is being signed.
* This must match the contentType parameter.
* <li>PKCS #9 Message-Digest, the digest of the content that is being
* signed. This must match the messageDigest parameter.
* </ul>
* After these two attributes are verified to be both present and correct,
* the encryptedDigest field of the SignerInfo is verified to be the
* signature of the contents octets of the DER encoding of the
* authenticatedAttributes field.
*/
private void verifyWithAuthenticatedAttributes(byte[] messageDigest, OBJECT_IDENTIFIER contentType, PublicKey pubkey) throws NotInitializedException, NoSuchAlgorithmException, InvalidKeyException, TokenException, SignatureException {
int numAttrib = authenticatedAttributes.size();
if (numAttrib < 2) {
throw new SignatureException("At least two authenticated attributes must be present:" + " content-type and message-digest");
}
// go through the authenticated attributes, verifying the
// interesting ones
boolean foundContentType = false;
boolean foundMessageDigest = false;
for (int i = 0; i < numAttrib; i++) {
if (!(authenticatedAttributes.elementAt(i) instanceof Attribute)) {
throw new SignatureException("Element of authenticatedAttributes is not an Attribute");
}
Attribute attrib = (Attribute) authenticatedAttributes.elementAt(i);
if (attrib.getType().equals(CONTENT_TYPE)) {
// content-type. Compare with what was passed in.
SET vals = attrib.getValues();
if (vals.size() != 1) {
throw new SignatureException("Content-Type attribute " + " does not have exactly one value");
}
ASN1Value val = vals.elementAt(0);
OBJECT_IDENTIFIER ctype;
try {
if (val instanceof OBJECT_IDENTIFIER) {
ctype = (OBJECT_IDENTIFIER) val;
} else if (val instanceof ANY) {
ctype = (OBJECT_IDENTIFIER) ((ANY) val).decodeWith(OBJECT_IDENTIFIER.getTemplate());
} else {
// what the heck is it? not what it's supposed to be
throw new InvalidBERException("Content-Type authenticated attribute has unexpected" + " content type");
}
} catch (InvalidBERException e) {
throw new SignatureException("Content-Type authenticated attribute does not have " + "OBJECT IDENTIFIER value");
}
// contentType parameter
if (!ctype.equals(contentType)) {
throw new SignatureException("Content-type in authenticated attributes does not " + "match content-type being verified");
}
// content type is A-OK
foundContentType = true;
} else if (attrib.getType().equals(MESSAGE_DIGEST)) {
SET vals = attrib.getValues();
if (vals.size() != 1) {
throw new SignatureException("Message-digest attribute does not have" + " exactly one value");
}
ASN1Value val = vals.elementAt(0);
byte[] mdigest;
try {
if (val instanceof OCTET_STRING) {
mdigest = ((OCTET_STRING) val).toByteArray();
} else if (val instanceof ANY) {
OCTET_STRING os;
os = (OCTET_STRING) ((ANY) val).decodeWith(OCTET_STRING.getTemplate());
mdigest = os.toByteArray();
} else {
// what the heck is it? not what it's supposed to be
throw new InvalidBERException("Content-Type authenticated attribute has unexpected" + " content type");
}
} catch (InvalidBERException e) {
throw new SignatureException("Message-digest attribute does not" + " have OCTET STRING value");
}
// message digest being verified
if (!byteArraysAreSame(mdigest, messageDigest)) {
throw new SignatureException("Message-digest attribute does not" + " match message digest being verified");
}
// message digest is A-OK
foundMessageDigest = true;
}
// we don't care about other attributes
}
if (!foundContentType) {
throw new SignatureException("Authenticated attributes does not contain" + " PKCS #9 content-type attribute");
}
if (!foundMessageDigest) {
throw new SignatureException("Authenticate attributes does not contain" + " PKCS #9 message-digest attribute");
}
SignatureAlgorithm sigAlg = SignatureAlgorithm.fromOID(digestEncryptionAlgorithm.getOID());
// All the authenticated attributes are present and correct.
// Now verify the signature.
CryptoToken token = CryptoManager.getInstance().getInternalCryptoToken();
Signature sig = token.getSignatureContext(sigAlg);
sig.initVerify(pubkey);
// verify the contents octets of the DER encoded authenticated attribs
byte[] toBeDigested;
toBeDigested = ASN1Util.encode(authenticatedAttributes);
MessageDigest md = MessageDigest.getInstance(DigestAlgorithm.fromOID(digestAlgorithm.getOID()).toString());
byte[] digest = md.digest(toBeDigested);
byte[] toBeVerified;
if (sigAlg.getRawAlg() == SignatureAlgorithm.RSASignature) {
// create DigestInfo structure
SEQUENCE digestInfo = new SEQUENCE();
digestInfo.addElement(new AlgorithmIdentifier(digestAlgorithm.getOID(), null));
digestInfo.addElement(new OCTET_STRING(digest));
toBeVerified = ASN1Util.encode(digestInfo);
} else {
toBeVerified = digest;
}
sig.update(toBeVerified);
if (!sig.verify(encryptedDigest.toByteArray())) {
// signature is invalid
throw new SignatureException("encryptedDigest was not the correct" + " signature of the contents octets of the DER-encoded" + " authenticated attributes");
}
// SUCCESSFULLY VERIFIED
}
use of com.google.protobuf2.Any in project jss by dogtagpki.
the class PFX method main.
public static void main(String[] args) {
try {
if (args.length != 2) {
System.out.println("Usage: PFX <dbdir> <infile>");
System.exit(-1);
}
int certfile = 0;
CryptoManager.initialize(args[0]);
// Decode the P12 file
PFX.Template pfxt = new PFX.Template();
PFX pfx;
FileInputStream fis = new FileInputStream(args[1]);
try (BufferedInputStream in = new BufferedInputStream(fis, 2048)) {
pfx = (PFX) pfxt.decode(in);
}
System.out.println("Decoded PFX");
// now peruse it for interesting info
System.out.println("Version: " + pfx.getVersion());
AuthenticatedSafes authSafes = pfx.getAuthSafes();
SEQUENCE asSeq = authSafes.getSequence();
System.out.println("AuthSafes has " + asSeq.size() + " SafeContents");
System.out.println("Enter password: ");
Password pass = Password.readPasswordFromConsole();
// get new password
System.out.println("Enter new password:");
Password newPass = Password.readPasswordFromConsole();
// verify the PFX
StringBuffer sb = new StringBuffer();
if (pfx.verifyAuthSafes(pass, sb)) {
System.out.println("AuthSafes verifies correctly");
} else {
System.out.println("AuthSafes failed to verify because: " + sb);
}
// get new AuthSafes ready
AuthenticatedSafes newAuthSafes = new AuthenticatedSafes();
for (int i = 0; i < asSeq.size(); i++) {
SEQUENCE safeContents = authSafes.getSafeContentsAt(pass, i);
System.out.println("\n\nSafeContents #" + i + " has " + safeContents.size() + " bags");
for (int j = 0; j < safeContents.size(); j++) {
SafeBag safeBag = (SafeBag) safeContents.elementAt(j);
System.out.println("\nBag " + j + " has type " + safeBag.getBagType());
SET attribs = safeBag.getBagAttributes();
if (attribs == null) {
System.out.println("Bag has no attributes");
} else {
for (int b = 0; b < attribs.size(); b++) {
Attribute a = (Attribute) attribs.elementAt(b);
if (a.getType().equals(SafeBag.FRIENDLY_NAME)) {
BMPString bs = (BMPString) ((ANY) a.getValues().elementAt(0)).decodeWith(BMPString.getTemplate());
System.out.println("Friendly Name: " + bs);
} else if (a.getType().equals(SafeBag.LOCAL_KEY_ID)) {
OCTET_STRING os = (OCTET_STRING) ((ANY) a.getValues().elementAt(0)).decodeWith(OCTET_STRING.getTemplate());
System.out.println("LocalKeyID:");
AuthenticatedSafes.print_byte_array(os.toByteArray());
} else {
System.out.println("Unknown attribute type");
}
}
}
ASN1Value val = safeBag.getInterpretedBagContent();
if (val instanceof PrivateKeyInfo) {
System.out.println("content is PrivateKeyInfo");
} else if (val instanceof EncryptedPrivateKeyInfo) {
EncryptedPrivateKeyInfo epki = ((EncryptedPrivateKeyInfo) val);
System.out.println("content is EncryptedPrivateKeyInfo, algoid:" + epki.getEncryptionAlgorithm().getOID());
PrivateKeyInfo pki = epki.decrypt(pass, new PasswordConverter());
byte[] salt = new byte[20];
JSSSecureRandom rand = CryptoManager.getInstance().getSecureRNG();
rand.nextBytes(salt);
epki = EncryptedPrivateKeyInfo.createPBE(PBEAlgorithm.PBE_SHA1_DES3_CBC, newPass, salt, 1, new PasswordConverter(), pki);
// replace the old safe bag with the new
safeContents.insertElementAt(new SafeBag(safeBag.getBagType(), epki, safeBag.getBagAttributes()), j);
safeContents.removeElementAt(j + 1);
} else if (val instanceof CertBag) {
System.out.println(" content is CertBag");
CertBag cb = (CertBag) val;
if (cb.getCertType().equals(CertBag.X509_CERT_TYPE)) {
OCTET_STRING os = (OCTET_STRING) cb.getInterpretedCert();
FileOutputStream fos = new FileOutputStream("cert" + (certfile++) + ".der");
os.encode(fos);
fos.close();
Certificate cert = (Certificate) ASN1Util.decode(Certificate.getTemplate(), os.toByteArray());
cert.getInfo().print(System.out);
} else {
System.out.println("Unrecognized cert type");
}
} else {
System.out.println("content is ANY");
}
}
// Add the new safe contents to the authsafes
if (authSafes.safeContentsIsEncrypted(i)) {
newAuthSafes.addEncryptedSafeContents(AuthenticatedSafes.DEFAULT_KEY_GEN_ALG, newPass, null, AuthenticatedSafes.DEFAULT_ITERATIONS, safeContents);
} else {
newAuthSafes.addSafeContents(safeContents);
}
}
// Create new PFX from new authsafes
PFX newPfx = new PFX(newAuthSafes);
newPfx.computeMacData(newPass, null, DEFAULT_ITERATIONS);
FileOutputStream fos = new FileOutputStream("newjss.p12");
newPfx.encode(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
use of com.google.protobuf2.Any in project jss by dogtagpki.
the class CertRepContent method encode.
@Override
public void encode(Tag implicitTag, OutputStream ostream) throws IOException {
SEQUENCE encoding = new SEQUENCE();
// create sequence of certificates
if (caPubs != null) {
SEQUENCE certs = new SEQUENCE();
for (int i = 0; i < caPubs.length; i++) {
certs.addElement(new ANY(SEQUENCE.TAG, caPubs[i]));
}
encoding.addElement(new Tag(1), certs);
}
encoding.addElement(response);
encoding.encode(implicitTag, ostream);
}
use of com.google.protobuf2.Any in project jss by dogtagpki.
the class IssuingDistributionPoint method setFullName.
/**
* Sets the <code>fullName</code> of the <code>DistributionPointName</code>. It may be set to <code>null</code>.
* If it is set to a non-null value, <code>relativeName</code> will be
* set to <code>null</code>, because at most one of these two attributes
* can be specified at a time.
*
* @exception GeneralNamesException If an error occurs encoding the
* name.
*/
public void setFullName(GeneralNames fullName) throws GeneralNamesException, IOException {
this.fullName = fullName;
if (fullName != null) {
// encode the name to catch any problems with it
DerOutputStream derOut = new DerOutputStream();
fullName.encode(derOut);
try {
ANY raw = new ANY(derOut.toByteArray());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
raw.encodeWithAlternateTag(Tag.get(0), bos);
fullNameEncoding = new ANY(bos.toByteArray());
} catch (InvalidBERException e) {
// in DerOutputStream
throw new GeneralNamesException(e.toString());
}
this.relativeName = null;
}
}
Aggregations