public virtual void TestParse_explicit_bad_encoded() { ByteArrayOutputStream b = new ByteArrayOutputStream(); b.Write(Sharpen.Runtime.GetBytesForString("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n" , "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("author F\u00f6r fattare <*****@*****.**> 1218123387 +0700\n" , "ISO-8859-1")); b.Write(Sharpen.Runtime.GetBytesForString("committer C O. Miter <*****@*****.**> 1218123390 -0500\n" , "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("encoding EUC-JP\n", "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("\n", "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("\u304d\u308c\u3044\n", "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("\n", "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("Hi\n", "UTF-8")); RevCommit c; c = new RevCommit(Id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); // bogus id c.ParseCanonical(new RevWalk(db), b.ToByteArray()); NUnit.Framework.Assert.AreEqual("Japanese (EUC)", c.Encoding.EncodingName); NUnit.Framework.Assert.AreEqual("F\u00f6r fattare", c.GetAuthorIdent().GetName()); NUnit.Framework.Assert.AreEqual("\u304d\u308c\u3044", c.GetShortMessage()); NUnit.Framework.Assert.AreEqual("\u304d\u308c\u3044\n\nHi\n", c.GetFullMessage()); }
/// <exception cref="System.IO.IOException"></exception> private void AssertFileContentsEqual(FilePath actFile, string @string) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); FileInputStream fis = null; byte[] buffer = new byte[100]; try { fis = new FileInputStream(actFile); int read = fis.Read(buffer); while (read > 0) { bos.Write(buffer, 0, read); read = fis.Read(buffer); } string content = Sharpen.Runtime.GetStringForBytes(bos.ToByteArray(), "UTF-8"); NUnit.Framework.Assert.AreEqual(@string, content); } finally { if (fis != null) { fis.Close(); } } }
/// <exception cref="System.IO.IOException"></exception> internal DirCacheEntry(byte[] sharedInfo, MutableInteger infoAt, InputStream @in, MessageDigest md) { // private static final int P_CTIME_NSEC = 4; // private static final int P_MTIME_NSEC = 12; // private static final int P_DEV = 16; // private static final int P_INO = 20; // private static final int P_UID = 28; // private static final int P_GID = 32; info = sharedInfo; infoOffset = infoAt.value; IOUtil.ReadFully(@in, info, infoOffset, INFO_LEN); int len; if (IsExtended) { len = INFO_LEN_EXTENDED; IOUtil.ReadFully(@in, info, infoOffset + INFO_LEN, INFO_LEN_EXTENDED - INFO_LEN); if ((GetExtendedFlags() & ~EXTENDED_FLAGS) != 0) { throw new IOException(MessageFormat.Format(JGitText.Get().DIRCUnrecognizedExtendedFlags , GetExtendedFlags().ToString())); } } else { len = INFO_LEN; } infoAt.value += len; md.Update(info, infoOffset, len); int pathLen = NB.DecodeUInt16(info, infoOffset + P_FLAGS) & NAME_MASK; int skipped = 0; if (pathLen < NAME_MASK) { path = new byte[pathLen]; IOUtil.ReadFully(@in, path, 0, pathLen); md.Update(path, 0, pathLen); } else { ByteArrayOutputStream tmp = new ByteArrayOutputStream(); { byte[] buf = new byte[NAME_MASK]; IOUtil.ReadFully(@in, buf, 0, NAME_MASK); tmp.Write(buf); } for (; ; ) { int c = @in.Read(); if (c < 0) { throw new EOFException(JGitText.Get().shortReadOfBlock); } if (c == 0) { break; } tmp.Write(c); } path = tmp.ToByteArray(); pathLen = path.Length; skipped = 1; // we already skipped 1 '\0' above to break the loop. md.Update(path, 0, pathLen); md.Update(unchecked((byte)0)); } // Index records are padded out to the next 8 byte alignment // for historical reasons related to how C Git read the files. // int actLen = len + pathLen; int expLen = (actLen + 8) & ~7; int padLen = expLen - actLen - skipped; if (padLen > 0) { IOUtil.SkipFully(@in, padLen); md.Update(nullpad, 0, padLen); } }
/// <summary> /// Decodes data from Base64 notation, automatically /// detecting gzip-compressed data and decompressing it. /// </summary> /// <remarks> /// Decodes data from Base64 notation, automatically /// detecting gzip-compressed data and decompressing it. /// </remarks> /// <param name="s">the string to decode</param> /// <param name="options">encode options such as URL_SAFE</param> /// <returns>the decoded data</returns> /// <exception cref="System.IO.IOException">if there is an error</exception> /// <exception cref="System.ArgumentNullException">if <tt>s</tt> is null</exception> /// <since>1.4</since> public static byte[] Decode(string s, int options) { if (s == null) { throw new ArgumentNullException("Input string was null."); } // end if byte[] bytes; try { bytes = Sharpen.Runtime.GetBytesForString(s, PreferredEncoding); } catch (UnsupportedEncodingException) { // end try bytes = Sharpen.Runtime.GetBytesForString(s); } // end catch //</change> // Decode bytes = Decode(bytes, 0, bytes.Length, options); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) bool dontGunzip = (options & DontGunzip) != 0; if ((bytes != null) && (bytes.Length >= 4) && (!dontGunzip)) { int head = ((int)bytes[0] & unchecked((int)(0xff))) | ((bytes[1] << 8) & unchecked( (int)(0xff00))); if (GZIPInputStream.GzipMagic == head) { ByteArrayInputStream bais = null; GZIPInputStream gzis = null; ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new ByteArrayOutputStream(); bais = new ByteArrayInputStream(bytes); gzis = new GZIPInputStream(bais); while ((length = gzis.Read(buffer)) >= 0) { baos.Write(buffer, 0, length); } // end while: reading input // No error? Get new bytes. bytes = baos.ToByteArray(); } catch (IOException e) { // end try Sharpen.Runtime.PrintStackTrace(e); } finally { // Just return originally-decoded bytes // end catch try { baos.Close(); } catch (Exception) { } try { gzis.Close(); } catch (Exception) { } try { bais.Close(); } catch (Exception) { } } } } // end finally // end if: gzipped // end if: bytes.length >= 2 return bytes; }
public virtual void TestParse_explicit_bad_encoded2() { ByteArrayOutputStream b = new ByteArrayOutputStream(); b.Write(Sharpen.Runtime.GetBytesForString("object 9788669ad918b6fcce64af8882fc9a81cb6aba67\n" , "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("type tree\n", "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("tag v1.2.3.4.5\n", "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("tagger F\u00f6r fattare <*****@*****.**> 1218123387 +0700\n" , "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("encoding ISO-8859-1\n", "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("\n", "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("\u304d\u308c\u3044\n", "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("\n", "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("Hi\n", "UTF-8")); RevTag c; c = new RevTag(Id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); c.ParseCanonical(new RevWalk(db), b.ToByteArray()); NUnit.Framework.Assert.AreEqual("F\u00f6r fattare", c.GetTaggerIdent().GetName()); NUnit.Framework.Assert.AreEqual("\u304d\u308c\u3044", c.GetShortMessage()); NUnit.Framework.Assert.AreEqual("\u304d\u308c\u3044\n\nHi\n", c.GetFullMessage()); }
public virtual void TestLeadingWhitespaces() { ByteArrayOutputStream bos1 = new ByteArrayOutputStream(); bos1.Write(Sharpen.Runtime.GetBytesForString(" \n\t")); bos1.Write(Sharpen.Runtime.GetBytesForString(CONTENT1)); FilePath file = CreateFile(bos1.ToByteArray()); FileBasedConfig config = new FileBasedConfig(file, FS.DETECTED); config.Load(); NUnit.Framework.Assert.AreEqual(ALICE, config.GetString(USER, null, NAME)); config.SetString(USER, null, NAME, BOB); config.Save(); ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); bos2.Write(Sharpen.Runtime.GetBytesForString(" \n\t")); bos2.Write(Sharpen.Runtime.GetBytesForString(CONTENT2)); Assert.AssertArrayEquals(bos2.ToByteArray(), IOUtil.ReadFully(file)); }
/// <summary>Overwrite (or create) a loose ref in the remote repository.</summary> /// <remarks> /// Overwrite (or create) a loose ref in the remote repository. /// <p> /// This method creates any missing parent directories, if necessary. /// </remarks> /// <param name="name"> /// name of the ref within the ref space, for example /// <code>refs/heads/pu</code>. /// </param> /// <param name="value">new value to store in this ref. Must not be null.</param> /// <exception cref="System.IO.IOException"> /// writing is not supported, or attempting to write the file /// failed, possibly due to permissions or remote disk full, etc. /// </exception> internal virtual void WriteRef(string name, ObjectId value) { ByteArrayOutputStream b; b = new ByteArrayOutputStream(Constants.OBJECT_ID_STRING_LENGTH + 1); value.CopyTo(b); b.Write('\n'); WriteFile(ROOT_DIR + name, b.ToByteArray()); }
// COPY: Copied from libcore.net.UriCodec /// <param name="convertPlus">true to convert '+' to ' '.</param> public static string Decode(string s, bool convertPlus, Encoding charset) { if (s.IndexOf('%') == -1 && (!convertPlus || s.IndexOf('+') == -1)) { return s; } StringBuilder result = new StringBuilder(s.Length); ByteArrayOutputStream @out = new ByteArrayOutputStream(); for (int i = 0; i < s.Length; ) { char c = s[i]; if (c == '%') { do { if (i + 2 >= s.Length) { throw new ArgumentException("Incomplete % sequence at: " + i); } int d1 = HexToInt(s[i + 1]); int d2 = HexToInt(s[i + 2]); if (d1 == -1 || d2 == -1) { throw new ArgumentException("Invalid % sequence " + Sharpen.Runtime.Substring(s, i, i + 3) + " at " + i); } @out.Write(unchecked((byte)((d1 << 4) + d2))); i += 3; } while (i < s.Length && s[i] == '%'); result.Append(charset.GetString(@out.ToByteArray())); @out.Reset(); } else { if (convertPlus && c == '+') { c = ' '; } result.Append(c); i++; } } return result.ToString(); }
/// <exception cref="System.IO.IOException"></exception> private IOException Error(string action, string key, HttpURLConnection c) { IOException err = new IOException(MessageFormat.Format(JGitText.Get().amazonS3ActionFailed , action, key, HttpSupport.Response(c), c.GetResponseMessage())); ByteArrayOutputStream b = new ByteArrayOutputStream(); byte[] buf = new byte[2048]; for (; ; ) { int n = c.GetErrorStream().Read(buf); if (n < 0) { break; } if (n > 0) { b.Write(buf, 0, n); } } buf = b.ToByteArray(); if (buf.Length > 0) { Sharpen.Extensions.InitCause(err, new IOException("\n" + Sharpen.Extensions.CreateString (buf))); } return err; }
/// <exception cref="System.IO.IOException"></exception> private void AssertNoCrLfHelper(string expect, string input) { byte[] inbytes = Sharpen.Runtime.GetBytesForString(input); byte[] expectBytes = Sharpen.Runtime.GetBytesForString(expect); for (int i = 0; i < 5; ++i) { byte[] buf = new byte[i]; ByteArrayInputStream bis = new ByteArrayInputStream(inbytes); InputStream @in = new AutoCRLFInputStream(bis, true); ByteArrayOutputStream @out = new ByteArrayOutputStream(); if (i > 0) { int n; while ((n = @in.Read(buf)) >= 0) { @out.Write(buf, 0, n); } } else { int c; while ((c = @in.Read()) != -1) { @out.Write(c); } } @out.Flush(); @in.Close(); @out.Close(); byte[] actualBytes = @out.ToByteArray(); NUnit.Framework.Assert.AreEqual(Encode(expectBytes), Encode(actualBytes), "bufsize=" + i); } }
/// <summary>Escape unprintable characters optionally URI-reserved characters</summary> /// <param name="s">The Java String to encode (may contain any character)</param> /// <param name="escapeReservedChars">true to escape URI reserved characters</param> /// <param name="encodeNonAscii">encode any non-ASCII characters</param> /// <returns>a URI-encoded string</returns> private static string Escape(string s, bool escapeReservedChars, bool encodeNonAscii ) { if (s == null) { return null; } ByteArrayOutputStream os = new ByteArrayOutputStream(s.Length); byte[] bytes; try { bytes = Sharpen.Runtime.GetBytesForString(s, Constants.CHARACTER_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } // cannot happen for (int i = 0; i < bytes.Length; ++i) { int b = bytes[i] & unchecked((int)(0xFF)); if (b <= 32 || (encodeNonAscii && b > 127) || b == '%' || (escapeReservedChars && reservedChars.Get(b))) { os.Write('%'); byte[] tmp = Constants.EncodeASCII(string.Format("{0:x2}", Sharpen.Extensions.ValueOf (b))); os.Write(tmp[0]); os.Write(tmp[1]); } else { os.Write(b); } } byte[] buf = os.ToByteArray(); return RawParseUtils.Decode(buf, 0, buf.Length); }
/// <exception cref="Sharpen.NoSuchAlgorithmException"></exception> public override byte[] EncryptDigest(byte[] digestValue, DigestAlgorithm digestAlgo , IDssPrivateKeyEntry keyEntry) { try { ByteArrayOutputStream digestInfo = new ByteArrayOutputStream(); //jbonilla: cambio de enum a clase. if (digestAlgo.Equals(DigestAlgorithm.SHA1)) { digestInfo.Write(Constants.SHA1_DIGEST_INFO_PREFIX); } else { if (digestAlgo.Equals(DigestAlgorithm.SHA256)) { digestInfo.Write(Constants.SHA256_DIGEST_INFO_PREFIX); } else { if (digestAlgo.Equals(DigestAlgorithm.SHA256)) { digestInfo.Write(Constants.SHA512_DIGEST_INFO_PREFIX); } } } digestInfo.Write(digestValue); //Sharpen.Cipher cipher = Sharpen.Cipher.GetInstance(keyEntry.GetSignatureAlgorithm // ().GetPadding()); IBufferedCipher cipher = CipherUtilities.GetCipher(keyEntry.GetSignatureAlgorithm ().GetPadding()); //cipher.Init(Sharpen.Cipher.ENCRYPT_MODE, ((KSPrivateKeyEntry)keyEntry).GetPrivateKey // ()); cipher.Init(true, ((KSPrivateKeyEntry)keyEntry).PrivateKey); return cipher.DoFinal(digestInfo.ToByteArray()); } catch (IOException e) { // Writing in a ByteArrayOutputStream. Should never happens. throw new RuntimeException(e); } /*catch (NoSuchPaddingException e) { throw new RuntimeException(e); }*/ catch (InvalidKeyException e) { throw new RuntimeException(e); } /*catch (IllegalBlockSizeException e) { throw new RuntimeException(e); } catch (BadPaddingException) { // More likely the password is not good. throw new BadPasswordException(BadPasswordException.MSG.PKCS12_BAD_PASSWORD); }*/ }
/// <exception cref="System.IO.IOException"></exception> private byte[] CompressPackFormat(int type, byte[] data) { byte[] hdr = new byte[64]; int rawLength = data.Length; int nextLength = (int)(((uint)rawLength) >> 4); hdr[0] = unchecked((byte)((nextLength > 0 ? unchecked((int)(0x80)) : unchecked((int )(0x00))) | (type << 4) | (rawLength & unchecked((int)(0x0F))))); rawLength = nextLength; int n = 1; while (rawLength > 0) { nextLength = (int)(((uint)nextLength) >> 7); hdr[n++] = unchecked((byte)((nextLength > 0 ? unchecked((int)(0x80)) : unchecked( (int)(0x00))) | (rawLength & unchecked((int)(0x7F))))); rawLength = nextLength; } ByteArrayOutputStream @out = new ByteArrayOutputStream(); @out.Write(hdr, 0, n); DeflaterOutputStream d = new DeflaterOutputStream(@out); d.Write(data); d.Finish(); return @out.ToByteArray(); }
/// <summary>Save the configuration as a Git text style configuration file.</summary> /// <remarks> /// Save the configuration as a Git text style configuration file. /// <p> /// <b>Warning:</b> Although this method uses the traditional Git file /// locking approach to protect against concurrent writes of the /// configuration file, it does not ensure that the file has not been /// modified since the last read, which means updates performed by other /// objects accessing the same backing file may be lost. /// </remarks> /// <exception cref="System.IO.IOException">the file could not be written.</exception> public override void Save() { byte[] @out; string text = ToText(); if (utf8Bom) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bos.Write(unchecked((int)(0xEF))); bos.Write(unchecked((int)(0xBB))); bos.Write(unchecked((int)(0xBF))); bos.Write(Sharpen.Runtime.GetBytesForString(text, RawParseUtils.UTF8_CHARSET.Name ())); @out = bos.ToByteArray(); } else { @out = Constants.Encode(text); } LockFile lf = new LockFile(GetFile(), fs); if (!lf.Lock()) { throw new LockFailedException(GetFile()); } try { lf.SetNeedSnapshot(true); lf.Write(@out); if (!lf.Commit()) { throw new IOException(MessageFormat.Format(JGitText.Get().cannotCommitWriteTo, GetFile ())); } } finally { lf.Unlock(); } snapshot = lf.GetCommitSnapshot(); hash = Hash(@out); // notify the listeners FireConfigChangedEvent(); }
/// <exception cref="System.IO.IOException"></exception> internal byte[] ToArray() { try { if (length >= 0) { byte[] r = new byte[(int)length]; IOUtil.ReadFully(@in, r, 0, r.Length); return r; } ByteArrayOutputStream r_1 = new ByteArrayOutputStream(); byte[] buf = new byte[2048]; int n; while ((n = @in.Read(buf)) >= 0) { r_1.Write(buf, 0, n); } return r_1.ToByteArray(); } finally { @in.Close(); } }
/// <exception cref="System.Exception"></exception> private static byte[] Entry(FileMode mode, string name, ObjectId id) { ByteArrayOutputStream @out = new ByteArrayOutputStream(); mode.CopyTo(@out); @out.Write(' '); @out.Write(Constants.Encode(name)); @out.Write(0); id.CopyRawTo(@out); return @out.ToByteArray(); }
public virtual void TestUTF8withBOM() { ByteArrayOutputStream bos1 = new ByteArrayOutputStream(); bos1.Write(unchecked((int)(0xEF))); bos1.Write(unchecked((int)(0xBB))); bos1.Write(unchecked((int)(0xBF))); bos1.Write(Sharpen.Runtime.GetBytesForString(CONTENT1, "UTF-8")); FilePath file = CreateFile(bos1.ToByteArray()); FileBasedConfig config = new FileBasedConfig(file, FS.DETECTED); config.Load(); NUnit.Framework.Assert.AreEqual(ALICE, config.GetString(USER, null, NAME)); config.SetString(USER, null, NAME, BOB); config.Save(); ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); bos2.Write(unchecked((int)(0xEF))); bos2.Write(unchecked((int)(0xBB))); bos2.Write(unchecked((int)(0xBF))); bos2.Write(Sharpen.Runtime.GetBytesForString(CONTENT2, "UTF-8")); Assert.AssertArrayEquals(bos2.ToByteArray(), IOUtil.ReadFully(file)); }
/// <exception cref="System.IO.IOException"></exception> private byte[] ReadFile(string patchFile) { InputStream @in = typeof(DiffFormatterReflowTest).GetResourceAsStream(patchFile); if (@in == null) { NUnit.Framework.Assert.Fail("No " + patchFile + " test vector"); return null; } // Never happens try { byte[] buf = new byte[1024]; ByteArrayOutputStream temp = new ByteArrayOutputStream(); int n; while ((n = @in.Read(buf)) > 0) { temp.Write(buf, 0, n); } return temp.ToByteArray(); } finally { @in.Close(); } }
/// <exception cref="System.Exception"></exception> private static byte[] Mktree(params byte[][] data) { ByteArrayOutputStream @out = new ByteArrayOutputStream(); foreach (byte[] e in data) { @out.Write(e); } return @out.ToByteArray(); }
/// <exception cref="System.IO.IOException"></exception> protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData , SignerInformation si, SignatureParameters parameters, Document originalData) { si = base.ExtendCMSSignature(signedData, si, parameters, originalData); DerObjectIdentifier attributeId = null; ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream(); switch (GetExtendedValidationType()) { case 1: { attributeId = PkcsObjectIdentifiers.IdAAEtsEscTimeStamp; toTimestamp.Write(si.GetSignature()); // We don't include the outer SEQUENCE, only the attrType and attrValues as stated by the TS §6.3.5, // NOTE 2) toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken] .AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken] .AttrValues.GetDerEncoded()); break; } case 2: { attributeId = PkcsObjectIdentifiers.IdAAEtsCertCrlTimestamp; break; } default: { throw new InvalidOperationException("CAdES-X Profile: Extended validation is set but no valid type (1 or 2)" ); } } toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs] .AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs] .AttrValues.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs] .AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs] .AttrValues.GetDerEncoded()); //IDictionary<DerObjectIdentifier, Attribute> unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); IDictionary unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); BcCms.Attribute extendedTimeStamp = GetTimeStampAttribute(attributeId, GetSignatureTsa( ), digestAlgorithm, toTimestamp.ToByteArray()); //unsignedAttrHash.Put(attributeId, extendedTimeStamp); unsignedAttrHash.Add(attributeId, extendedTimeStamp); return SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable(unsignedAttrHash )); }