Objective C AES encrypt equal to java version - objective-c

I have java code to encrypt a password,
public static String encryptToString(String content,String password) throws IOException {
return parseByte2HexStr(encrypt(content, password));
}
private static byte[] encrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password.getBytes());
kgen.init(128, secureRandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(byteContent);
return result;
} catch (Exception e) {
log.error(e.getMessage(),e);
}
return null;
}
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
Now I need to encrypt/decrypt it with objective-c, I do a lot of search and none method would generate the same encrypted output.
What's the objective-c version code equal to java code?
test case: encryptToString("test","password") => DA180930496EC69BFEBA923B7311037A

I believe the answers to this question are what you are looking for: Any cocoa source code for AES encryption decryption?
I adapted a function somebody posted as answer: https://gist.github.com/4335132
To use:
NSString *content = #"test";
NSData *dataToEncrypt = [content dataUsingEncoding:NSUTF8StringEncoding];
NSData *data = [dataToEncrypt AES128EncryptWithKey:#"password"];
NSString *hex = [data hexString];
It's not exactly the same because your Java code does not use the password itself for encrypting but uses it to seed a random number generator. But I think that this should still work with what you are trying to do.

Related

Itext7 PDF Sign Problem - The document has been altered or corrupted since the signature was applied

I have a program that signs pdf's via smartcard. Right now there is a new card that I need to integrate, but there is an error with the signature of the PDF (The document has been altered or corrupted since the signature was applied).
Error
I thought this is strange since there is no such error with the other cards..
The only difference between the cards is that this new one I use iaik to get the sign hash and not direct APDU commands, so, I'm in doubt if the signing problem is related with my implementation of the IAIK or I just need to change the way of signing with Itext 7 on this particular card.
Here is some code:
public byte[] signPDFDocument(byte[] pdfData, String requestKey, String requestIV, UserCertificates uc, String xLocation, String yLocation, String height, String width, String pageToSign) throws IOException{
int numPageToSign = Integer.parseInt(pageToSign);
InputStream inputStream = new ByteArrayInputStream(pdfData);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
PdfReader reader = new PdfReader(inputStream);
PdfSigner pdfSigner = new PdfSigner(reader, outStream, new StampingProperties());
//check page to sign not outOfBounds
if(numPageToSign > pdfSigner.getDocument().getNumberOfPages() || numPageToSign <= 0)
{
numPageToSign = 1;
}
//Certs Chain
Certificate[] certChain = new Certificate[1];
certChain[0] = uc.getCert();
// Create the signature appearance
PdfFont font = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
PdfFont fontBold = PdfFontFactory.createFont(FontConstants.TIMES_BOLD);
Rectangle rect = new Rectangle(Integer.parseInt(xLocation), Integer.parseInt(yLocation), Integer.parseInt(width), Integer.parseInt(height));
PdfSignatureAppearance signatureAppearance = pdfSigner.getSignatureAppearance();
signatureAppearance
// Specify if the appearance before field is signed will be used
// as a background for the signed field. The "false" value is the default value.
.setReuseAppearance(false)
.setPageRect(rect)
.setPageNumber(numPageToSign)
.setReasonCaption("")
.setLocationCaption("");
pdfSigner.setFieldName("signature");
PdfFormXObject n0 = signatureAppearance.getLayer0();
PdfCanvas n0Canvas = new PdfCanvas(n0, pdfSigner.getDocument());
PdfFormXObject n2 = signatureAppearance.getLayer2();
Canvas n2Canvas = new Canvas(n2, pdfSigner.getDocument());
CertificateInfo.X500Name x500name = CertificateInfo.getSubjectFields((X509Certificate)certChain[0]);
String name = null;
if (x500name != null) {
name = x500name.getField("CN");
if (name == null)
name = x500name.getField("E");
}
//Signature
Text first = new Text("Assinado por: ").setFont(font).setFontSize(9);
Text second = new Text(name).setFontSize(8).setFont(fontBold);
Paragraph paragraph = new Paragraph().add(first).add(second);
paragraph.setMarginBottom(0.07f);
n2Canvas.add(paragraph);
//Date
Text date = new Text("Data: ").setFont(font).setFontSize(9);
Text date2 = new Text(new SimpleDateFormat("dd-MM-yyyy HH:mm Z").format(Calendar.getInstance().getTime())).setFont(fontBold).setFontSize(8);
paragraph = new Paragraph().add(date).add(date2);
n2Canvas.add(paragraph);
n2Canvas.close();
IExternalDigest digest = new BouncyCastleDigest();
IExternalSignature externalSignature = new SmartCardSignaturePDF();
// IExternalSignature externalSignature = new PrivateKeySignature(pk,"SHA-256",p.getName());
// OCSPVerifier ocspVerifier = new OCSPVerifier(null, null);
// IOcspClient ocspClient = new OcspClientBouncyCastle(ocspVerifier);
try {
pdfSigner.signDetached(digest, externalSignature, certChain, null, null, null, 0, CryptoStandard.CADES);
} catch (IOException | GeneralSecurityException e) {
}
return outStream.toByteArray();
}
And the External Signature
public class SmartCardSignaturePDF implements IExternalSignature{
#Override
public String getHashAlgorithm() {
return DigestAlgorithms.SHA256;
}
#Override
public String getEncryptionAlgorithm() {
return "RSA";
}
#Override
public byte[] sign(byte[] message) throws GeneralSecurityException {
try {
return signData(MessageDigest.getInstance("SHA-256").digest(message));
} catch (HardwareException | SignatureException e) {
}
return null;
}
}
And the code for the signature from the card
private byte[] signData(byte[] input_data) throws HardwareException {
//Key Mechanism, Label and ID
Mechanism KeyPairGenerationMechanism = Mechanism.get(PKCS11Constants.CKM_RSA_PKCS);
char [] signTemplate = "Sign".toCharArray();
byte[] id = "Sign".getBytes();
//Private Key Template
RSAPrivateKey rsaPrivateKeyTemplate = new RSAPrivateKey();
//rsaPrivate
rsaPrivateKeyTemplate.getToken().setBooleanValue(Boolean.TRUE);
rsaPrivateKeyTemplate.getId().setByteArrayValue(id);
rsaPrivateKeyTemplate.getLabel().setCharArrayValue(signTemplate);
//Public Key Template
RSAPublicKey rsaPublicKeyTemplate = new RSAPublicKey();
//rsaPublicKeyTemplate.getVerify().setBooleanValue(value);
rsaPublicKeyTemplate.getToken().setBooleanValue(Boolean.TRUE);
rsaPublicKeyTemplate.getId().setByteArrayValue(id);
rsaPublicKeyTemplate.getLabel().setCharArrayValue(signTemplate);
try {
this.cegerCardsession.findObjectsInit(rsaPrivateKeyTemplate);
PKCS11Object[] key = this.cegerCardsession.findObjects(1024);
if(key.length == 0)
{
KeyPairGenerationMechanism = Mechanism.get(PKCS11Constants.CKM_RSA_PKCS_KEY_PAIR_GEN);
KeyPair keyPair = this.cegerCardsession.generateKeyPair(KeyPairGenerationMechanism, rsaPublicKeyTemplate, rsaPrivateKeyTemplate);
KeyPairGenerationMechanism = Mechanism.get(PKCS11Constants.CKM_RSA_PKCS);
this.cegerCardsession.signInit(KeyPairGenerationMechanism, keyPair.getPrivateKey());
}
else
{
PrivateKey PKey = new PrivateKey();
PKey = (PrivateKey) key[0];
this.cegerCardsession.signInit(KeyPairGenerationMechanism, PKey);
}
byte[] signedData = this.cegerCardsession.sign(input_data);
return signedData;
} catch (TokenException e) {
throw new HardwareException(e.getMessage(), e.getCause());
}
}
Also, a link with a signed pdf file and the original one
Pdf's
I'm completly stuck for several days now and I have no idea on how to fix this :S

Library to verify OAuth 1.0a signature in ASP.NET Core

I need to validate OAuth 1.0a (RFC 5849) requests on an ASP.NET Core site. Upgrading the client to OAuth 2.0 or anything else is not an option. I understand the spec, but implementing the verification process for the oauth_signature seems like it would be a bit fragile, and surely there's no need to reinvent the wheel here.
Does .NET Core have any built-in classes for handling this? Ideally, something where you just pass in the HttpRequest and the secret key and it tells you if the signature is valid?
If there's nothing built in, any recommendations on third-party libraries that could handle this for me?
I really didn't feel comfortable taking a dependency hit on this one by bringing in a third-party NuGet package. Many of the options provided far more than I needed, and most were (understandably) no longer in active development or supported. Taking on an unsupported "black box" dependency with anything related to security doesn't sit quite right with me.
So I rolled my own implementation for just the subset of features that I needed to support (verification only, and OAuth parameters passed as form post data). This is not meant to be a complete implementation, but can serve as a starting point for anyone else who finds themselves in a similar situation and isn't interested in bringing in a dependency.
The latest code is on GitHub.
public static class OAuth1Utilities
{
private static readonly Lazy<bool[]> UnreservedCharacterMask = new Lazy<bool[]>(CreateUnreservedCharacterMask);
public static string EncodeString(string value)
{
byte[] characterBytes = Encoding.UTF8.GetBytes(value);
StringBuilder encoded = new StringBuilder();
foreach (byte character in characterBytes)
{
if (UnreservedCharacterMask.Value[character])
{
encoded.Append((char)character);
}
else
{
encoded.Append($"%{character:X2}");
}
}
return encoded.ToString();
}
public static string GetBaseStringUri(HttpRequest request)
{
StringBuilder baseStringUri = new StringBuilder();
baseStringUri.Append(request.Scheme.ToLowerInvariant());
baseStringUri.Append("://");
baseStringUri.Append(request.Host.ToString().ToLowerInvariant());
baseStringUri.Append(request.Path.ToString().ToLowerInvariant());
return baseStringUri.ToString();
}
public static string GetNormalizedParameterString(HttpRequest request)
{
var parameters = new List<(string key, string value)>();
foreach (var queryItem in request.Query)
{
foreach (var queryValue in queryItem.Value)
{
parameters.Add((queryItem.Key, queryValue));
}
}
foreach (var formItem in request.Form)
{
foreach (var formValue in formItem.Value)
{
parameters.Add((formItem.Key, formValue));
}
}
parameters.RemoveAll(_ => _.key == "oauth_signature");
parameters = parameters
.Select(_ => (key: EncodeString(_.key), value: EncodeString(_.value)))
.OrderBy(_ => _.key)
.ThenBy(_ => _.value).ToList();
return string.Join("&", parameters.Select(_ => $"{_.key}={_.value}"));
}
public static string GetSignature(HttpRequest request, string clientSharedSecret, string tokenSharedSecret)
{
string signatureBaseString = GetSignatureBaseString(request);
return GetSignature(signatureBaseString, clientSharedSecret, tokenSharedSecret);
}
public static string GetSignature(string signatureBaseString, string clientSharedSecret, string tokenSharedSecret)
{
string key = $"{EncodeString(clientSharedSecret)}&{EncodeString(tokenSharedSecret)}";
var signatureAlgorithm = new HMACSHA1(Encoding.ASCII.GetBytes(key));
byte[] digest = signatureAlgorithm.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString));
return Convert.ToBase64String(digest);
}
public static string GetSignatureBaseString(HttpRequest request)
{
StringBuilder signatureBaseString = new StringBuilder();
signatureBaseString.Append(request.Method.ToUpperInvariant());
signatureBaseString.Append("&");
signatureBaseString.Append(EncodeString(GetBaseStringUri(request)));
signatureBaseString.Append("&");
signatureBaseString.Append(EncodeString(GetNormalizedParameterString(request)));
return signatureBaseString.ToString();
}
public static bool VerifySignature(HttpRequest request, string clientSharedSecret, string tokenSharedSecret)
{
string actualSignature = request.Form["oauth_signature"];
string expectedSignature = GetSignature(request, clientSharedSecret, tokenSharedSecret);
return expectedSignature == actualSignature;
}
private static bool[] CreateUnreservedCharacterMask()
{
bool[] mask = new bool[byte.MaxValue];
// hyphen
mask[45] = true;
// period
mask[46] = true;
// 0-9
for (int pos = 48; pos <= 57; pos++)
{
mask[pos] = true;
}
// A-Z
for (int pos = 65; pos <= 90; pos++)
{
mask[pos] = true;
}
// underscore
mask[95] = true;
// a-z
for (int pos = 97; pos <= 122; pos++)
{
mask[pos] = true;
}
// tilde
mask[126] = true;
return mask;
}
}

SHA-256 with salt for hashing produces different values for signature in java

We have to build a signature string hashed using SHA-256 with random salt and using 10000 iterations. However, when I run the below code with salt, output hash value is not matching at all for the same input string. If I run the code without the salt, hashed value matches. Can someone point out the right way to add a random salt to the SHA-256 digest and get the firstValue/secondValue same below.
import java.security.MessageDigest;
import java.security.SecureRandom;
import org.springframework.security.crypto.codec.Hex;
public class someTester{
public static void main(String[] args) {
String signatureInput = "someStringWhichisSensitive";
String firstSignValue = getSignature(signatureInput);
String secondSignValue = getSignature(signatureInput);
System.out.println("firstSignValue="+firstSignValue);
System.out.println("secondSignValue="+secondSignValue);
}
private static String getSignature(String signatureInput){
MessageDigest md;
String signatureValue = null;
try {
// Create a random salt
SecureRandom sr = new SecureRandom();
byte[] bSalt = new byte[8];
sr.nextBytes(bSalt);
md = MessageDigest.getInstance("SHA-256");
// digest.update(bSalt);
byte[] bDigest = md.digest(signatureInput.getBytes());
// Iterate through 10000 times
for (int i = 0; i < 10000; i++) {
bDigest = md.digest(bDigest);
}
signatureValue = new String(Hex.encode(bDigest));
} catch (Exception e) {
System.out.println("Exception while calculating SHA-256 digest value"+e);
}
return signatureValue;
}
}

Adding a new Extension to my generated certificate

I need to add a new Extension of OID 1.3.6.1.5.5.7.1.26 in my certificate. I got this OID extension in my certificate but with the following error:
Certificate Extensions: 10
[1]: ObjectId: 1.3.6.1.5.5.7.1.26 Criticality=false
Extension unknown: DER encoded OCTET string =
0000: 04 0C 30 0A 13 08 33 39 20 64 63 20 32 62 ..0...
39 dc 2b
I want this OID to be recognized similar to other extensions like AuthorityInfoAccess, etc.
Do I need to edit the jar of Bouncy Castle X509 class?
Im using ACME4j as a client and Letsencrypt Boulder as my server.
Here is the CSR Builder code for signing up the certificate.
public void sign(KeyPair keypair) throws IOException {
//Security.addProvider(new BouncyCastleProvider());
Objects.requireNonNull(keypair, "keypair");
if (namelist.isEmpty()) {
throw new IllegalStateException("No domain was set");
}
try {
GeneralName[] gns = new GeneralName[namelist.size()];
for (int ix = 0; ix < namelist.size(); ix++) {
gns[ix] = new GeneralName(GeneralName.dNSName,namelist.get(ix));
}
SignatureAlgorithmIdentifierFinder algFinder = new
DefaultSignatureAlgorithmIdentifierFinder();
GeneralNames subjectAltName = new GeneralNames(gns);
PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(namebuilder.build(), keypair.getPublic());
ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
extensionsGenerator.addExtension(Extension.subjectAlternativeName, false, subjectAltName);
//extensionsGenerator.addExtension(Extension.authorityInfoAccess, true, subjectAltName);
//extensionsGenerator.addExtension(new ASN1ObjectIdentifier("TBD"), false, subjectAltName);
//extensionsGenerator.addExtension(new ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.24"), false, subjectAltName);
extensionsGenerator.addExtension(new ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.26").intern(), false, subjectAltName);
//extentionsGenerator.addExtension();
p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate());
PrivateKey pk = keypair.getPrivate();
/*JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(
pk instanceof ECKey ? EC_SIGNATURE_ALG : EC_SIGNATURE_ALG);
ContentSigner signer = csBuilder.build(pk);*/
if(pk instanceof ECKey)
{
AlgorithmIdentifier sigAlg = algFinder.find("SHA1withECDSA");
AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().
find(sigAlg);
ContentSigner signer = new JcaContentSignerBuilder("SHA256with"+pk.getAlgorithm()).setProvider(BOUNCY_CASTL E_PROVIDER).build(keypair.getPrivate());
csr=p10Builder.build(signer);
System.out.println("ZIPED CSR ECDSA: "+csr);
}
else
{
ContentSigner signer = new JcaContentSignerBuilder("SHA256with"+pk.getAlgorithm()).build(keypair.getPrivate ());
csr = p10Builder.build(signer);
System.out.println("ZIPED CSR RSA: "+csr);
}
//csr = p10Builder.build(signer);
} catch (Exception ex) {
ex.printStackTrace();;
}
}
Note: for these codes I used bcprov-jdk15on 1.56
Some comments about your code. First of all, note the ASN1 structure:
TNAuthorizationList ::= SEQUENCE SIZE (1..MAX) OF TNEntry
TNEntry ::= CHOICE {
spc [0] ServiceProviderCodeList,
range [1] TelephoneNumberRange,
one E164Number
}
Note that TNEntry is a choice, and TNAuthorizationList is a sequence of TNEntry objects. So your class name should be changed to TNEntry. In the code below, please remember that I've changed the class name to TNEntry.
I've also changed some things in this class. In getInstance(Object obj) method, the types of spc and range fields are incorrect (according to ASN1 definition, they are both sequences):
switch (tag) {
case spc:
case range: // both are sequences
return new TNEntry(tag, ASN1Sequence.getInstance(tagObj, false));
// not sure about "one" field, as it's not tagged
}
I just don't know how to handle the one field, as it's not tagged. Maybe it should be a DERIA5String, or maybe there's another type for "untagged" choices.
In this same class (remember, I've changed its name to TNEntry), I also removed the constructor public TNEntry(int tag, String name) because I'm not sure if it applies (at least I didn't need to use it, but you can keep it if you want), and I've changed toString method to return a more readable string:
public String toString() {
String sep = System.getProperty("line.separator");
StringBuffer buf = new StringBuffer();
buf.append(this.getClass().getSimpleName());
buf.append(" [").append(tag);
buf.append("]: ");
switch (tag) {
case spc:
buf.append("ServiceProviderCodeList: ").append(sep);
ASN1Sequence seq = (ASN1Sequence) this.obj;
int size = seq.size();
for (int i = 0; i < size; i++) {
// all elements are DERIA5Strings
DERIA5String str = (DERIA5String) seq.getObjectAt(i);
buf.append(" ");
buf.append(str.getString());
buf.append(sep);
}
break;
case range:
buf.append("TelephoneNumberRange: ").append(sep);
// there are always 2 elements in TelephoneNumberRange
ASN1Sequence s = (ASN1Sequence) this.obj;
DERIA5String str = (DERIA5String) s.getObjectAt(0);
buf.append(" start: ");
buf.append(str.getString());
buf.append(sep);
ASN1Integer count = (ASN1Integer) s.getObjectAt(1);
buf.append(" count: ");
buf.append(count.toString());
buf.append(sep);
break;
default:
buf.append(obj.toString());
}
return buf.toString();
}
And I also created a TNAuthorizationList class, which holds the sequence of TNEntry objects (remember that I've changed your class name to TNEntry, so this TNAuthorizationList class is a different one). Note that I also created a constant to hold the OID (just to make things a little bit easier):
public class TNAuthorizationList extends ASN1Object {
// put OID in a constant, so I don't have to remember it all the time
public static final ASN1ObjectIdentifier TN_AUTH_LIST_OID = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.26");
private TNEntry[] entries;
public TNAuthorizationList(TNEntry[] entries) {
this.entries = entries;
}
public static TNAuthorizationList getInstance(Object obj) {
if (obj instanceof TNAuthorizationList) {
return (TNAuthorizationList) obj;
}
if (obj != null) {
return new TNAuthorizationList(ASN1Sequence.getInstance(obj));
}
return null;
}
public static TNAuthorizationList getInstance(ASN1TaggedObject obj, boolean explicit) {
return getInstance(ASN1Sequence.getInstance(obj, explicit));
}
private TNAuthorizationList(ASN1Sequence seq) {
this.entries = new TNEntry[seq.size()];
for (int i = 0; i != seq.size(); i++) {
entries[i] = TNEntry.getInstance(seq.getObjectAt(i));
}
}
public TNEntry[] getEntries() {
TNEntry[] tmp = new TNEntry[entries.length];
System.arraycopy(entries, 0, tmp, 0, entries.length);
return tmp;
}
#Override
public ASN1Primitive toASN1Primitive() {
return new DERSequence(entries);
}
public String toString() {
String sep = System.getProperty("line.separator");
StringBuffer buf = new StringBuffer();
buf.append(this.getClass().getSimpleName());
buf.append(":").append(sep);
for (TNEntry tnEntry : entries) {
buf.append(" ");
buf.append(tnEntry.toString());
buf.append(sep);
}
return buf.toString();
}
}
Now, to add this extension to a certificate, I've done this code (with some sample data as I don't know what should be in each field in a real world situation):
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(etc...);
// create TNEntries for TNAuthorizationList
TNEntry[] entries = new TNEntry[2];
// create a "spc" entry
DERIA5String[] cList = new DERIA5String[] { new DERIA5String("spc1"), new DERIA5String("spc2") };
DERSequence spc = new DERSequence(cList);
entries[0] = TNEntry.getInstance(new DERTaggedObject(false, TNEntry.spc, spc));
// create a "range" entry
DERSequence range = new DERSequence(new ASN1Encodable[] { new DERIA5String("123456"), new ASN1Integer(1) });
entries[1] = TNEntry.getInstance(new DERTaggedObject(false, TNEntry.range, range));
TNAuthorizationList tnAuthList = new TNAuthorizationList(entries);
builder.addExtension(TNAuthorizationList.TN_AUTH_LIST_OID, false, tnAuthList);
Once you have the certificate object (a X509Certificate in my example), you can do:
// cert is a X509Certificate instance
ASN1Primitive value = X509ExtensionUtil.fromExtensionValue(cert.getExtensionValue(TNAuthorizationList.TN_AUTH_LIST_OID.getId()));
TNAuthorizationList authList = TNAuthorizationList.getInstance(value);
System.out.println(authList.toString());
The output will be:
TNAuthorizationList:
TNEntry [0]: ServiceProviderCodeList:
spc1
spc2
TNEntry [1]: TelephoneNumberRange:
start: 123456
count: 1
Notes:
As I said, this code is incomplete because I'm not sure how to handle the one field of TNEntry, because it's not tagged (I don't know if it must be a DERIA5String or if there's another type of object for an "untagged" field).
You could also do some improvements:
ServiceProviderCodeList can have 1 to 3 elements, so you could validate its size
TelephoneNumberRange: the start field has a specific format (FROM ("0123456789#*") which I think it means only these characters are accepted), so you could also validate it
To create the values for ServiceProviderCodeList and TelephoneNumberRange, I've created the DERSequence objects by hand, but you can create custom classes for them if you want: ServiceProviderCodeList could hold a list of DERIA5String and perform proper validations in its constructor (size from 1 to 3), and TelephoneNumberRange could have start and count fields (with proper validation of start value) - and toASN1Primitive just need to return a DERSequence of its fields in the right order
For your parsing issues, I've checked acme4j code and it uses a java.security.cert.X509Certificate class. The toString() method of this class (when using Sun's default provider) is generating this "extension unknown" output (according to the corresponding code).
So, in order to parse it correctly (show the formatted output as described above), you'll probably have to change acme4j's code (or write your own), creating a new toString() method and include the new TNAuthorizationList classes in this method.
When you provide the code showing how you're using acme4j, I'll update this answer accordingly, if needed.
As the OID 1.3.6.1.5.5.7.1.26 is still a draft, I believe it's very unlikely that tools and systems like Let's Encrypt recognize this extension (they'll probably do it after this extension becomes official, and I really don't know the bureaucratic process behind such approvals).
Which means you'll probably have to code it. I've been using Bouncy Castle for a couple of years but never had to create a new ASN1 structure. But if I had to, I'd take a look at its source code as an initial guidance.
Considering the ASN1 structure of this extension:
TNAuthorizationList ::= SEQUENCE SIZE (1..MAX) OF TNEntry
TNEntry ::= CHOICE {
spc [0] ServiceProviderCodeList,
range [1] TelephoneNumberRange,
one E164Number
}
ServiceProviderCodeList ::= SEQUENCE SIZE (1..3) OF IA5String
-- Service Provider Codes may be OCNs, various SPIDs, or other
-- SP identifiers from the telephone network
TelephoneNumberRange ::= SEQUENCE {
start E164Number,
count INTEGER
}
E164Number ::= IA5String (SIZE (1..15)) (FROM ("0123456789#*"))
The extension value must be a SEQUENCE of TNEntry. So you could use ASN1Sequence (or its subclass DERSequence) and put instances of TNEntry inside it.
To create a TNEntry, you need to implement ASN1Choice (take a look at source of GeneralName class and do something similar).
And so on, until you have the whole structure mapped to their respective classes, using Bouncy Castle built-in classes to support you (there are DERIA5String for IA5String and DERInteger for INTEGER, which can be used in ServiceProviderCodeList and TelephoneNumberRange)
After that you can build your own parser, which can recognize this extension. But as I said, don't expect other tools to recognize it.
Right now, for testing purpose , Im just passing a string value from my CA Boulder. So to read that, this is the custom ASN1 Object STructure for TNAUthList.
public class TNAuthorizationList extends ASN1Object implements ASN1Choice{
public static final int spc = 0;
public static final int range = 1;
private ASN1Encodable obj;
private int tag;
public TNAuthorizationList(
int tag,
ASN1Encodable name)
{
this.obj = name;
this.tag = tag;
}
public TNAuthorizationList(
int tag,
String name)
{
this.tag = tag;
if (tag == spc)
{
this.obj = new DERIA5String(name);
}
else if (tag == range)
{
this.obj = new ASN1ObjectIdentifier(name);
}
else
{
throw new IllegalArgumentException("can't process String for tag: " + tag);
}
}
public static TNAuthorizationList getInstance(
Object obj)
{
if (obj == null || obj instanceof TNAuthorizationList)
{
return (TNAuthorizationList)obj;
}
if (obj instanceof ASN1TaggedObject)
{
ASN1TaggedObject tagObj = (ASN1TaggedObject)obj;
int tag = tagObj.getTagNo();
switch (tag)
{
case spc:
return new TNAuthorizationList(tag, DERIA5String.getInstance(tagObj, false));
}
}
if (obj instanceof byte[])
{
try
{
return getInstance(ASN1Primitive.fromByteArray((byte[])obj));
}
catch (IOException e)
{
throw new IllegalArgumentException("unable to parse encoded general name");
}
}
throw new IllegalArgumentException("unknown object in getInstance: " + obj.getClass().getName());
}
public static TNAuthorizationList getInstance(
ASN1TaggedObject tagObj,
boolean explicit)
{
return TNAuthorizationList.getInstance(ASN1TaggedObject.getInstance(tagObj, true));
}
public int getTagNo()
{
return tag;
}
public ASN1Encodable getSpc()
{
return obj;
}
public String toString()
{
StringBuffer buf = new StringBuffer();
buf.append(tag);
buf.append(": ");
switch (tag)
{
case spc:
buf.append(DERIA5String.getInstance(obj).getString());
break;
default:
buf.append(obj.toString());
}
return buf.toString();
}
/**
*TNEntry ::= CHOICE {
* spc [0] ServiceProviderCodeList,
* range [1] TelephoneNumberRange,
* one E164Number
* }
*/
#Override
public ASN1Primitive toASN1Primitive() {
// TODO Auto-generated method stub
return new DERTaggedObject(false, tag, obj);
}
}
As You suggested I have passed the OID value to X509Util class and printed the Output.
ASN1Object o = X509ExtensionUtil.fromExtensionValue(cert.getExtensionValue("1.3.6.1.5.5.7.1.26"));
System.out.println("ASN1 Object: "+o);
System.out.println("get Class "+o.getClass());
and the O/P is
ASN1 Object: [SPID : 39 dc 2b]
get Class class org.bouncycastle.asn1.DLSequence
Is this fine. How do i parse this with my custom ASN1 Structure?
This is how im using ACME4j.
public class RSASignedCertificate {
private static final int KEY_SIZE = 2048;
private static final Logger LOG = Logger.getLogger(CCIDClient.class);
#SuppressWarnings("unused")
public void fetchCertificate(String domain,String spid, String email, int port,
String username, String password, String certPath) throws Exception {
// Load or create a key pair for the user's account
boolean createdNewKeyPair = true;
KeyPair domainKeyPair = null;
DomainKeyStore details = null;
KeyPair userKeyPair = null;
userKeyPair = KeyPairUtils.createKeyPair(KEY_SIZE);
DateFormat dateTime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date;
details = new DomainKeyStore();
// Create Hibernate Util class Object
// dao=new HibernateDAO();
boolean isDomainExist = new HibernateDAO().isDomainExist(domain);
if (isDomainExist) {
details.setDomain(domain);
details.setEmail(email);
date = new Date();
details.setUpdatedOn(dateTime.parse(dateTime.format(date)));
boolean updateresult = new HibernateDAO().updateDetails(details);
LOG.info("User Details Updated ");
}
else {
date = new Date();
// Date currentDateTime = dateTime.parse(dateTime.format(date));
details.setEmail(email);
details.setDomain(domain);
details.setStatus("Not Registered");
details.setCreatedOn(dateTime.parse(dateTime.format(date)));
details.setUpdatedOn(dateTime.parse(dateTime.format(date)));
boolean isInserted = new HibernateDAO().insertDetails(details);
if (!isInserted) {
throw new AcmeException("Unable to insert details");
}
LOG.info("User Details inserted ");
}
// details=dao.getDetails(domain);
Session session = null;
if (userKeyPair != null) {
session = new Session("http://192.168.1.143:4000/directory", userKeyPair);
System.out.println(session.getServerUri().toString());
System.out.println(session.resourceUri(Resource.NEW_REG));
}
Registration reg = null;
try {
reg = new RegistrationBuilder().create(session);
LOG.info("Registered a new user, URI: " + reg.getLocation());
} catch (AcmeConflictException ex) {
reg = Registration.bind(session, ex.getLocation());
LOG.info("Account does already exist, URI: " + reg.getLocation());
}
date = new Date();
details.setStatus("Registered");
details.setRegistrationDate(dateTime.parse(dateTime.format(date)));
details.setUpdatedOn(dateTime.parse(dateTime.format(date)));
new HibernateDAO().updateRegistration(details);
URI agreement = reg.getAgreement();
LOG.info("Terms of Service: " + agreement);
if (createdNewKeyPair) {
boolean accepted = acceptAgreement(reg, agreement);
if (!accepted) {
return;
}
}
Authorization auth = null;
try {
auth = reg.authorizeDomain(spid);
} catch (AcmeUnauthorizedException ex) {
// Maybe there are new T&C to accept?
boolean accepted = acceptAgreement(reg, agreement);
if (!accepted) {
return;
}
// Then try again...
auth = reg.authorizeDomain(spid);
}
LOG.info("New authorization for domain " + spid);
LOG.info("Authorization " + auth);
Challenge challenge = tokenChallenge(auth);
// System.out.println("Challendg status before trigger :"+challenge.getStatus());
if (challenge == null) {
throw new AcmeException("No Challenge found");
}
if (challenge.getStatus() == Status.VALID) {
return;
}
challenge.trigger();
int attempts = 1;
// System.out.println("Challendg status after trigger :"+challenge.getStatus());
while (challenge.getStatus() != Status.VALID && attempts-- > 0) {
// System.out.println(challenge.getStatus());
if (challenge.getStatus().equals(Status.PENDING)) {
challenge.update();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
LOG.warn("interrupted", e);
e.printStackTrace();
}
}
if (challenge.getStatus() == Status.INVALID) {
LOG.error("Challenge failed... Giving up.");
throw new AcmeServerException("Challenge Failed");
}
try {
Thread.sleep(3000L);
} catch (InterruptedException ex) {
LOG.warn("interrupted", ex);
}
challenge.update();
}
if (challenge.getStatus() != Status.VALID) {
LOG.error("Failed to pass the challenge... Giving up.");
throw new AcmeServerException("Challenge Failed");
}
date = new Date();
details.setStatus("Clallenge Completed");
details.setUpdatedOn(dateTime.parse(dateTime.format(date)));
new HibernateDAO().updateChallenge(details);
domainKeyPair = KeyPairUtils.createKeyPair(KEY_SIZE);
// Generate a CSR for the domain
CSRBuilder csrb = new CSRBuilder();
csrb.addDomains(spid);
csrb.sign(domainKeyPair);
// System.out.println("CSR:" +csrb.getCSR());
LOG.info("Keys Algorithm: "
+ domainKeyPair.getPrivate().getAlgorithm());
PrivateKeyStore privatekey = new PrivateKeyStore();
privatekey.setDomain(spid);
privatekey.setEmail(email);
privatekey.setPrivateKey(domainKeyPair.getPrivate().getEncoded());
PublicKeyStore publickey = new PublicKeyStore();
publickey.setDomain(spid);
publickey.setEmail(email);
publickey.setPublicKey(domainKeyPair.getPublic().getEncoded());
// Request a signed certificate
Certificate certificate = reg.requestCertificate(csrb.getEncoded());
LOG.info("Success! The certificate for spids " + spid
+ " has been generated!");
LOG.info("Certificate URI: " + certificate.getLocation());
String nameFile = spid.replace(".", "") + ".cer";
X509Certificate sscert = CertificateUtils.createTlsSniCertificate(domainKeyPair,spid);
System.out.println("Certificate :" +sscert);
ASN1Primitive o = X509ExtensionUtil.fromExtensionValue(sscert.getExtensionValue(TNAuthorizationList.TN_AUTH_LIST_OID.getId()));
System.out.println("ASN1:Object "+o+" class: "+o.getClass());
TNAuthorizationList TNList = TNAuthorizationList.getInstance(o);
System.out.println(TNList.toString());
File createFile = new File(certPath + nameFile);
if (!createFile.exists()) {
createFile.createNewFile();
}
try (FileWriter fw = new FileWriter(createFile.getAbsoluteFile())) {
CertificateUtils.writeX509Certificate(sscert, fw);
System.out.println("Certificate " + sscert);
System.out.println("Certificate Content" + fw);
}
date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, 90);
details.setIssueDate(dateTime.parse(dateTime.format(date)));
details.setUpdatedOn(dateTime.parse(dateTime.format(date)));
details.setValidUntil(dateTime.parse(dateTime.format(c.getTime())));
details.setStatus("Issued");
details.setCertPath(certPath + nameFile);
new HibernateDAO().updateCertificate(details);
}
public boolean acceptAgreement(Registration reg, URI agreement) throws AcmeException
{
reg.modify().setAgreement(agreement).commit();
LOG.info("Updated user's ToS");
return true;
}
public Challenge tokenChallenge(Authorization auth)
{
TokenChallenge chall = auth.findChallenge(TokenChallenge.TYPE);
LOG.info("File name: " + chall.getType());
//LOG.info("Content: " + chall.`);
return chall;
}

How to create HMACSHA256 api signature in Salesforce Apex

Can somebody help in creating HMACSHA256 api signature in apex using crypto class. Corresponding java code is given below :-
public static void main(String[] args) throws GeneralSecurityException, IOException {
String secretKey = "secretKey";
String salt = "0123456789";
String generateHmacSHA256Signature = generateHmacSHA256Signature(salt, secretKey);
System.out.println("Signature: " + generateHmacSHA256Signature);
String urlEncodedSign = URLEncoder.encode(generateHmacSHA256Signature, "UTF-8");
System.out.println("Url encoded value: " + urlEncodedSign);
}
public static String generateHmacSHA256Signature(String data, String key) throws GeneralSecurityException {
byte[] hmacData = null;
try {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(secretKey);
hmacData = mac.doFinal(data.getBytes("UTF-8"));
return new Base64Encoder().encode(hmacData);
} catch (UnsupportedEncodingException e) {
throw new GeneralSecurityException(e);
}
}
Thanks in advance
http://boards.developerforce.com/t5/Apex-Code-Development/How-to-create-HMACSHA256-api-signature/td-p/551055
I think that'll do it for you?
Copied here for posterity (in case the link dies)
AKK's answer:
"Re: How to create HMACSHA256 api signature
‎12-28-2012 02:58 AM
Sorry for unformatted code, actually I was looking into how to format but didn't find anything in mozilla and when login through chrome editor appeared.
I got the signature right using below code maybe this helps someone :-
public void genrateSignature() {
String salt = String.valueOf(Crypto.getRandomInteger());
String secretKey = 'secret_key';
String signature = generateHmacSHA256Signature(salt, secretKey);
System.debug('Signature : '+signature);
}
private static String generateHmacSHA256Signature(String saltValue, String secretKeyValue) {
String algorithmName = 'HmacSHA256';
Blob hmacData = Crypto.generateMac(algorithmName, Blob.valueOf(saltValue), Blob.valueOf(secretKeyValue));
return EncodingUtil.base64Encode(hmacData);
}
Thanks"