use of sun.misc.BASE64Encoder in project jdk8u_jdk by JetBrains.
the class V3Certificate method test.
public static boolean test(String algorithm, String sigAlg, int keyLength) throws IOException, NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException, SignatureException {
byte[] issuerId = { 1, 2, 3, 4, 5 };
byte[] subjectId = { 6, 7, 8, 9, 10 };
boolean testResult = true;
// Subject and Issuer
X500Name subject = new X500Name("test", "Oracle", "Santa Clara", "US");
X500Name issuer = subject;
// Generate keys and sign
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
keyGen.initialize(keyLength);
KeyPair pair = keyGen.generateKeyPair();
PublicKey publicKey = pair.getPublic();
PrivateKey privateKey = pair.getPrivate();
MessageDigest md = MessageDigest.getInstance("SHA");
byte[] keyId = md.digest(publicKey.getEncoded());
Signature signature = Signature.getInstance(sigAlg);
signature.initSign(privateKey);
// Validity interval
Date firstDate = new Date();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("PST"));
cal.set(2014, 03, 10, 12, 30, 30);
Date lastDate = cal.getTime();
CertificateValidity interval = new CertificateValidity(firstDate, lastDate);
// Certificate Info
X509CertInfo cert = new X509CertInfo();
cert.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
cert.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber((int) (firstDate.getTime() / 1000)));
cert.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(AlgorithmId.get(sigAlg)));
cert.set(X509CertInfo.SUBJECT, subject);
cert.set(X509CertInfo.KEY, new CertificateX509Key(publicKey));
cert.set(X509CertInfo.VALIDITY, interval);
cert.set(X509CertInfo.ISSUER, issuer);
cert.set(X509CertInfo.ISSUER_ID, new UniqueIdentity(new BitArray(issuerId.length * 8 - 2, issuerId)));
cert.set(X509CertInfo.SUBJECT_ID, new UniqueIdentity(subjectId));
// Create Extensions
CertificateExtensions exts = new CertificateExtensions();
GeneralNameInterface mailInf = new RFC822Name("test@Oracle.com");
GeneralName mail = new GeneralName(mailInf);
GeneralNameInterface dnsInf = new DNSName("Oracle.com");
GeneralName dns = new GeneralName(dnsInf);
GeneralNameInterface uriInf = new URIName("http://www.Oracle.com");
GeneralName uri = new GeneralName(uriInf);
// localhost
byte[] address = new byte[] { 127, 0, 0, 1 };
GeneralNameInterface ipInf = new IPAddressName(address);
GeneralName ip = new GeneralName(ipInf);
int[] oidData = new int[] { 1, 2, 3, 4 };
GeneralNameInterface oidInf = new OIDName(new ObjectIdentifier(oidData));
GeneralName oid = new GeneralName(oidInf);
SubjectAlternativeNameExtension subjectName = new SubjectAlternativeNameExtension();
IssuerAlternativeNameExtension issuerName = new IssuerAlternativeNameExtension();
GeneralNames subjectNames = (GeneralNames) subjectName.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
GeneralNames issuerNames = (GeneralNames) issuerName.get(IssuerAlternativeNameExtension.ISSUER_NAME);
subjectNames.add(mail);
subjectNames.add(dns);
subjectNames.add(uri);
issuerNames.add(ip);
issuerNames.add(oid);
cal.set(2000, 11, 15, 12, 30, 30);
lastDate = cal.getTime();
PrivateKeyUsageExtension pkusage = new PrivateKeyUsageExtension(firstDate, lastDate);
KeyUsageExtension usage = new KeyUsageExtension();
usage.set(KeyUsageExtension.CRL_SIGN, true);
usage.set(KeyUsageExtension.DIGITAL_SIGNATURE, true);
usage.set(KeyUsageExtension.NON_REPUDIATION, true);
KeyIdentifier kid = new KeyIdentifier(keyId);
SerialNumber sn = new SerialNumber(42);
AuthorityKeyIdentifierExtension aki = new AuthorityKeyIdentifierExtension(kid, subjectNames, sn);
SubjectKeyIdentifierExtension ski = new SubjectKeyIdentifierExtension(keyId);
BasicConstraintsExtension cons = new BasicConstraintsExtension(true, 10);
PolicyConstraintsExtension pce = new PolicyConstraintsExtension(2, 4);
exts.set(SubjectAlternativeNameExtension.NAME, subjectName);
exts.set(IssuerAlternativeNameExtension.NAME, issuerName);
exts.set(PrivateKeyUsageExtension.NAME, pkusage);
exts.set(KeyUsageExtension.NAME, usage);
exts.set(AuthorityKeyIdentifierExtension.NAME, aki);
exts.set(SubjectKeyIdentifierExtension.NAME, ski);
exts.set(BasicConstraintsExtension.NAME, cons);
exts.set(PolicyConstraintsExtension.NAME, pce);
cert.set(X509CertInfo.EXTENSIONS, exts);
// Generate and sign X509CertImpl
X509CertImpl crt = new X509CertImpl(cert);
crt.sign(privateKey, sigAlg);
crt.verify(publicKey);
try (FileOutputStream fos = new FileOutputStream(new File(V3_FILE));
FileOutputStream fos_b64 = new FileOutputStream(new File(V3_B64_FILE));
PrintWriter pw = new PrintWriter(fos_b64)) {
crt.encode((OutputStream) fos);
fos.flush();
// Certificate boundaries/
pw.println("-----BEGIN CERTIFICATE-----");
pw.flush();
new BASE64Encoder().encodeBuffer(crt.getEncoded(), fos_b64);
fos_b64.flush();
pw.println("-----END CERTIFICATE-----");
}
out.println("*** Certificate ***");
out.println(crt);
out.println("*** End Certificate ***");
X509Certificate x2 = generateCertificate(V3_FILE);
if (!x2.equals(crt)) {
out.println("*** Certificate mismatch ***");
testResult = false;
}
X509Certificate x3 = generateCertificate(V3_B64_FILE);
if (!x3.equals(crt)) {
out.println("*** Certificate mismatch ***");
testResult = false;
}
return testResult;
}
use of sun.misc.BASE64Encoder in project jdk8u_jdk by JetBrains.
the class TestBase64Golden method test0.
public static void test0(Base64Type type, Encoder encoder, Decoder decoder, String srcFile, String encodedFile) throws Exception {
String[] srcLns = Files.readAllLines(Paths.get(SRCDIR, srcFile), DEF_CHARSET).toArray(new String[0]);
String[] encodedLns = Files.readAllLines(Paths.get(SRCDIR, encodedFile), DEF_CHARSET).toArray(new String[0]);
int lns = 0;
for (String srcStr : srcLns) {
String encodedStr = null;
if (type != Base64Type.MIME) {
encodedStr = encodedLns[lns++];
} else {
while (lns < encodedLns.length) {
String s = encodedLns[lns++];
if (s.length() == 0)
break;
if (encodedStr != null) {
encodedStr += DEFAULT_CRLF + s;
} else {
encodedStr = s;
}
}
if (encodedStr == null && srcStr.length() == 0) {
encodedStr = "";
}
}
System.out.printf("%n src[%d]: %s%n", srcStr.length(), srcStr);
System.out.printf("encoded[%d]: %s%n", encodedStr.length(), encodedStr);
byte[] srcArr = srcStr.getBytes(DEF_CHARSET);
byte[] encodedArr = encodedStr.getBytes(DEF_CHARSET);
ByteBuffer srcBuf = ByteBuffer.wrap(srcArr);
ByteBuffer encodedBuf = ByteBuffer.wrap(encodedArr);
byte[] resArr = new byte[encodedArr.length];
// test int encode(byte[], byte[])
int len = encoder.encode(srcArr, resArr);
assertEqual(len, encodedArr.length);
assertEqual(resArr, encodedArr);
// test byte[] encode(byte[])
resArr = encoder.encode(srcArr);
assertEqual(resArr, encodedArr);
// test ByteBuffer encode(ByteBuffer)
int limit = srcBuf.limit();
ByteBuffer resBuf = encoder.encode(srcBuf);
assertEqual(srcBuf.position(), limit);
assertEqual(srcBuf.limit(), limit);
assertEqual(resBuf, encodedBuf);
// reset for next test
srcBuf.rewind();
// test String encodeToString(byte[])
String resEncodeStr = encoder.encodeToString(srcArr);
assertEqual(resEncodeStr, encodedStr);
// test int decode(byte[], byte[])
resArr = new byte[srcArr.length];
len = decoder.decode(encodedArr, resArr);
assertEqual(len, srcArr.length);
assertEqual(resArr, srcArr);
// test byte[] decode(byte[])
resArr = decoder.decode(encodedArr);
assertEqual(resArr, srcArr);
// test ByteBuffer decode(ByteBuffer)
limit = encodedBuf.limit();
resBuf = decoder.decode(encodedBuf);
assertEqual(encodedBuf.position(), limit);
assertEqual(encodedBuf.limit(), limit);
assertEqual(resBuf, srcBuf);
// reset for next test
encodedBuf.rewind();
// test byte[] decode(String)
resArr = decoder.decode(encodedStr);
assertEqual(resArr, srcArr);
// test compatible with sun.misc.Base64Encoder
if (type == Base64Type.MIME) {
sun.misc.BASE64Encoder miscEncoder = new BASE64Encoder();
sun.misc.BASE64Decoder miscDecoder = new BASE64Decoder();
resArr = decoder.decode(miscEncoder.encode(srcArr));
assertEqual(resArr, srcArr);
resArr = encoder.encode(miscDecoder.decodeBuffer(encodedStr));
assertEqual(new String(resArr, DEF_CHARSET), encodedStr);
}
}
}
use of sun.misc.BASE64Encoder in project jdk8u_jdk by JetBrains.
the class Obj method encodeReference.
/**
* Convert a Reference object into several LDAP attributes.
*
* A Reference is stored as into the following attributes:
* javaClassName
* value: Reference.getClassName();
* javaFactory
* value: Reference.getFactoryClassName();
* javaCodeBase
* value: Reference.getFactoryClassLocation();
* javaReferenceAddress
* value: #0#typeA#valA
* value: #1#typeB#valB
* value: #2#typeC##[serialized RefAddr C]
* value: #3#typeD#valD
*
* where
* - the first character denotes the separator
* - the number following the first separator denotes the position
* of the RefAddr within the Reference
* - "typeA" is RefAddr.getType()
* - ## denotes that the Base64-encoded form of the non-StringRefAddr
* is to follow; otherwise the value that follows is
* StringRefAddr.getContents()
*
* The default separator is the hash character (#).
* May provide property for this in future.
*/
private static Attributes encodeReference(char separator, Reference ref, Attributes attrs, Object orig) throws NamingException {
if (ref == null)
return attrs;
String s;
if ((s = ref.getClassName()) != null) {
attrs.put(new BasicAttribute(JAVA_ATTRIBUTES[CLASSNAME], s));
}
if ((s = ref.getFactoryClassName()) != null) {
attrs.put(new BasicAttribute(JAVA_ATTRIBUTES[FACTORY], s));
}
if ((s = ref.getFactoryClassLocation()) != null) {
attrs.put(new BasicAttribute(JAVA_ATTRIBUTES[CODEBASE], s));
}
// specified other type names
if (orig != null && attrs.get(JAVA_ATTRIBUTES[TYPENAME]) != null) {
Attribute tAttr = LdapCtxFactory.createTypeNameAttr(orig.getClass());
if (tAttr != null) {
attrs.put(tAttr);
}
}
int count = ref.size();
if (count > 0) {
Attribute refAttr = new BasicAttribute(JAVA_ATTRIBUTES[REF_ADDR]);
RefAddr refAddr;
BASE64Encoder encoder = null;
for (int i = 0; i < count; i++) {
refAddr = ref.get(i);
if (refAddr instanceof StringRefAddr) {
refAttr.add("" + separator + i + separator + refAddr.getType() + separator + refAddr.getContent());
} else {
if (encoder == null)
encoder = new BASE64Encoder();
refAttr.add("" + separator + i + separator + refAddr.getType() + separator + separator + encoder.encodeBuffer(serializeObject(refAddr)));
}
}
attrs.put(refAttr);
}
return attrs;
}
use of sun.misc.BASE64Encoder in project paascloud-master by paascloud.
the class HttpAesUtil method encrypt.
/**
* 加密
*
* @param contentParam 需要加密的内容
* @param keyParam 加密密码
* @param md5Key 是否对key进行md5加密
* @param ivParam 加密向量
*
* @return 加密后的字节数据 string
*/
public static String encrypt(String contentParam, String keyParam, boolean md5Key, String ivParam) {
try {
byte[] content = contentParam.getBytes(CHAR_SET);
byte[] key = keyParam.getBytes(CHAR_SET);
byte[] iv = ivParam.getBytes(CHAR_SET);
if (md5Key) {
MessageDigest md = MessageDigest.getInstance("MD5");
key = md.digest(key);
}
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
// "算法/模式/补码方式"
Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
// 使用CBC模式, 需要一个向量iv, 可增加加密算法的强度
IvParameterSpec ivps = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivps);
byte[] bytes = cipher.doFinal(content);
return new BASE64Encoder().encode(bytes);
} catch (Exception ex) {
log.error("加密密码失败", ex);
throw new HttpAesException("加密失败");
}
}
Aggregations